Javascript syntax is the set of rules that dictate how programs written in Javascript should be structured.
Declare variables using let, const, or var:
// 'variable' declaration using let keyword. let age = 20; // 'variable' declaration using const keyword. const name = 'Alice'; // 'variable' declaration using var keyword. var count = 10; // 'var' is older and has some difference in scoping
// 'variable' storing integer value. let num = 12; // 'variable' storing string value. let text = 'Hello World, javascript!'; // 'variable' storing boolean value. let flag = false; // 'variable' storing object as value. let personObj = { name: 'Alice', age: 20 }; // 'variable' storing array as value. let colors = ['red', 'green', 'blue']; // 'variable' storing function as value. let functionName = function() { /* function body can be added inside curly braces */ };
Javascript has several built-in data types, including numbers, strings, booleans, objects, arrays, and more.
// Arithmetic Operator, storing difference of two values. let difference = 12 - 10; // Arithmetic Operator, storing sum of two values. let sum = 12 + 7; // Assignment Operator decrement value by 1. let decrement = sum--; // Assignment Operator Increment value by 1. let increment = sum ++; // Comparison Operator. let isGreaterThan = 10 > 5; // Logical Operator. let logicalAnd = true && false;
// if else statements if (x > 10) { // code block } else { // code block } // for loop statements for (let i = 0; i < 10; i++) { // code block } // while loop statements while (x < 10) { // code block x += 1; }
Arithmetic, comparison, logical, and assignment operators are used for various operations:
let employee = { name: "Alice", age: 23, isStudent: false };
class Employee { constructor(name, age, isStudent) { this.name = name; this.age = age; this.isStudent = isStudent; } } // Creating instance of Employee class to access properties and behaviour let employee = new Employee("Alice", 23, false); console.log(employee.name, employee.age);
Javascript supports conditional statements (if-else), loops (for, while, do-while), switch-case and more.
Objects are collections of key-value pairs. It can hold any type of value.
Javascript supports class-based object-oriented programming after classes introduced in ES6.