Basic Syntax and Variables
-
Variables: Variables are containers for storing data values. You can declare variables using
var
,let
, orconst
.javascriptvar name = "John"; // var is function-scoped
let age = 30; // let is block-scoped
const isStudent = true; // const is block-scoped and cannot be reassigned
-
Data Types: JavaScript supports several data types including:
- Primitive types:
String
,Number
,Boolean
,Null
,Undefined
,Symbol
, andBigInt
- Objects:
Object
,Array
,Function
, etc.
javascriptlet stringExample = "Hello World";
let numberExample = 42;
let booleanExample = true;
let nullExample = null;
let undefinedExample;
let symbolExample = Symbol('symbol');
let bigintExample = BigInt(12345678901234567890);
- Primitive types:
2. Operators
-
Arithmetic Operators: Used to perform arithmetic on numbers.
javascriptlet x = 5;
let y = 2;
console.log(x + y); // Addition
console.log(x - y); // Subtraction
console.log(x * y); // Multiplication
console.log(x / y); // Division
console.log(x % y); // Modulus
-
Assignment Operators: Used to assign values to variables.
javascriptlet a = 10;
a += 5; // Equivalent to a = a + 5
a -= 3; // Equivalent to a = a - 3
-
Comparison Operators: Used to compare values.
javascriptconsole.log(5 == "5"); // true (equality without type checking)
console.log(5 === "5"); // false (equality with type checking)
console.log(5 != "5"); // false
console.log(5 !== "5"); // true
-
Logical Operators: Used to perform logical operations.
javascriptlet isTrue = true;
let isFalse = false;
console.log(isTrue && isFalse); // Logical AND
console.log(isTrue || isFalse); // Logical OR
console.log(!isTrue); // Logical NOT
3. Control Structures
-
Conditional Statements: Used to perform different actions based on different conditions.
javascriptlet hour = 20;
if (hour < 18) {
console.log("Good day");
} else {
console.log("Good evening");
}
-
Switch Statement: An alternative to using multiple
if...else
statements.javascriptlet day = 2;
switch (day) {
case 0:
console.log("Sunday");
break;
case 1:
console.log("Monday");
break;
default:
console.log("Some other day");
}
-
Loops: Used to repeat a block of code multiple times.
-
For Loop: Repeats a block of code a specified number of times.
javascriptfor (let i = 0; i < 5; i++) {
console.log(i);
}Conclusion
Understanding these fundamental concepts of JavaScript is crucial for developing more advanced skills and building robust web applications. Practice these basics regularly, and you’ll be well on your way to mastering JavaScript.
-