JavaScript is a cross-platform, object-oriented scripting language.
It is a small and lightweight language.
console.log('Hello World');
Variables store data values.
Declare variables with let, const, or var.
let x = 5;
- var: function scope
- let: block scope
- const: block scope, immutable
JavaScript has dynamic types.
Primitive types include:
let num = 10; // Number
- String
- Number
- Boolean
- Null
- Undefined
- Symbol
Functions are blocks of reusable code.
Use function keyword or arrow syntax.
function greet() { return 'Hello'; }
const greet = () => 'Hello';
Loops execute code repeatedly.
Common loops: for, while, do...while.
for (let i = 0; i < 5; i++) { }
while (i < 5) { }
do { } while (i < 5);
Conditional statements execute code based on conditions.
Use if, else if, else statements.
if (x > 5) { console.log('x is greater than 5'); }
if (x > 5) { console.log('x is greater than 5'); } else { console.log('x is less than or equal to 5'); }
Arrays store collections of data.
Use square brackets [] to declare arrays.
let arr = [1, 2, 3];
- Indexing: access elements by index
- Methods: push, pop, shift, unshift, splice, slice, join, concat
Objects store collections of key-value pairs.
Use curly brackets {} to declare objects.
let obj = { name: 'John', age: 30 };
- Properties: access values by key
- Methods: constructor, hasOwnProperty, isPrototypeOf
Classes define blueprints for objects.
Use class keyword to declare classes.
class Person { constructor(name, age) { this.name = name; this.age = age; } }
Inheritance allows classes to inherit properties and methods.
Use extends keyword to inherit classes.
class Employee extends Person { constructor(name, age, salary) { super(name, age); this.salary = salary; } }
Modules allow code to be organized into reusable files.
Use import and export keywords to work with modules.
import { add } from './math.js';
export function add(x, y) { return x + y; }