JavaScript Basics
JavaScript Syntax
JavaScript syntax is the set of rules that define how a JavaScript program is written and interpreted.
- JavaScript is case-sensitive
- Statements end with a semicolon
;(optional, but recommended) - Statements are executed top to bottom, left to right
let message = "Hello!";
console.log(message);
JavaScript Statements
A statement is a line of code that performs an action.
let x = 10; // Statement 1
x = x + 5; // Statement 2
console.log(x); // Statement 3
Multiple statements can be grouped using curly braces {} (called a code block):
{
let name = "John";
console.log(name);
}
JavaScript Comments
Comments are used to explain code and are ignored by the browser.
- Single-line comment:
// This is a single-line comment
- Multi-line comment:
/* This is a
multi-line comment */
Variables in JavaScript
Variables store data values. You can declare them using:
var (Old way)
var name = "Alice";
let (Modern, block-scoped)
let age = 25;
const (Constant - value cannot change)
const country = "India";
| Keyword | Can Reassign? | Scope Type |
|---|---|---|
| var | Yes | Function-level |
| let | Yes | Block-level |
| const | No | Block-level |
JavaScript Data Types
JavaScript is dynamically typed, meaning you don't need to declare a data type.
Primitive Types:
String-"Hello"Number-42,3.14Boolean-true,falseUndefined- variable declared but not assignedNull- intentional absence of valueSymbol- unique identifiers (advanced use cases)BigInt- very large numbers (added in ES2020)
Non-Primitive Types:
ObjectArrayFunction
let name = "Tom"; // String
let age = 30; // Number
let isOnline = true; // Boolean
let person = {name: "Tom", age: 30}; // Object
JavaScript Operators
JavaScript supports several kinds of operators:
1. Arithmetic Operators
+ - * / % ** ++ --
2. Assignment Operators
= += -= *= /= %= **=
3. Comparison Operators
== === != !== > < >= <=
==checks value only===checks value and type (recommended)
4. Logical Operators
&& || !
true && false // false
true || false // true
!false // true
5. String Concatenation Operator
let fullName = "John" + " " + "Doe"; // "John Doe"
Type Conversion (Casting)
๐ Implicit (Automatic)
let result = "5" + 2; // "52" (number 2 converted to string)
๐ Explicit (Manual)
Number("10"); // 10
String(20); // "20"
Boolean(0); // false
typeof Operator
Used to check the type of a variable.
typeof "hello"; // "string"
typeof 5; // "number"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof null; // "object" (a quirk in JavaScript)
๐งช Practice Tip:
Create a small script that:
- Declares variables using
letandconst - Uses arithmetic and logical operators
- Outputs results with
console.log()
Example:
let a = 10;
let b = 5;
let sum = a + b;
console.log("Sum:", sum);
console.log("Are both greater than 0?", a > 0 && b > 0);