Understand JavaScript statements (variables, operators, functions)

Resources | Subject Notes | Information Technology IT

JavaScript Statements

JavaScript Statements: Variables, Operators, and Functions

Introduction

This section explores fundamental concepts in JavaScript programming: variables, operators, and functions. Understanding these elements is crucial for building interactive and dynamic web applications.

Variables

Variables are used to store data. In JavaScript, you declare variables using the keywords var, let, or const.

  • var: Declares a variable with function scope.
  • let: Declares a variable with block scope. Can be reassigned.
  • const: Declares a constant variable. Its value cannot be reassigned after initialization.

Example:

Declaration Scope Reassignable
var myVariable = 10; Function Scope Yes
let myVariable = 10; Block Scope Yes
const myConstant = 10; Block Scope No

Example of variable assignment:

let age = 30;
age = 31; // Reassignment is allowed with let and var
//myConstant = 32; // This would cause an error because myConstant is const

Operators

Operators are symbols that perform operations on values. JavaScript supports various types of operators:

  • Arithmetic Operators: + (addition), - (subtraction), * (multiplication), / (division), % (modulo).
  • Assignment Operators: = (assignment), += (addition assignment), -= (subtraction assignment), etc.
  • Comparison Operators: == (equal to), != (not equal to), === (strict equal to), !== (strict not equal to), > (greater than), < (less than), >= (greater than or equal to), <= (less than or equal to).
  • Logical Operators: && (AND), || (OR), ! (NOT).

Example of operators in use:

let a = 10;
let b = 5;

let sum = a + b; // Addition
let difference = a - b; // Subtraction
let product = a * b; // Multiplication
let quotient = a / b; // Division
let remainder = a % b; // Modulo

let isEqual = (a == b); // Strict equality check
let isNotEqual = (a !== b); // Strict inequality check

let isTrue = (a > b) && (a < 20); // Logical AND
let isEitherTrue = (a > b) || (a < 20); // Logical OR
let isNotTrue = !isTrue; // Logical NOT

Functions

Functions are reusable blocks of code that perform a specific task. They can accept input (parameters) and return output (return values).

Functions are declared using the function keyword.

Example:

function greet(name) {
  return "Hello, " + name + "!";
}

let message = greet("Alice");
console.log(message); // Output: Hello, Alice!

function add(x, y) {
  return x + y;
}

let result = add(5, 3);
console.log(result); // Output: 8

Functions can also be declared using arrow function syntax (ES6):

const multiply = (x, y) => x * y;
let product = multiply(4, 6);
console.log(product); // Output: 24

Conclusion

Variables, operators, and functions are the building blocks of JavaScript. Mastering these concepts is essential for developing web applications with dynamic behavior.