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
Javascript has several built-in data types, including numbers, strings, booleans, objects, arrays, and more.
'num' variable storing integer value.
let num = 12;
'text' variable storing string value.
let text = 'Hello World, javascript!';
'flag' variable storing boolean value.
let flag = false;
The 'personObj' variable storing the object as the value.
let personObj = { name: 'Alice', age: 20 };
'colors' variable storing array as value.
let colors = ['red', 'green', 'blue'];
'functionName' variable storing function as the value.
let functionName = function() { /* function body can be added inside curly braces */ };
Arithmetic, comparison, logical, and assignment operators are used for various operations:
Subtract Operator, storing difference of two values.
let difference = 12 - 10;
Addition Operator, storing the 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 ++;
let isGreaterThan = 10 > 5;
let logicalAnd = true && false;
Javascript supports conditional statements (if-else), loops (for, while, do-while), switch-case and more.
if (x > 10) { // code block } else { // code block }
for (let i = 0; i < 10; i++) { // code block }
while (x < 10) { // code block x += 1; }
Objects are collections of key-value pairs. It can hold any type of value.
let employee = { name: "Alice", age: 23, isStudent: false };
Javascript supports class-based object-oriented programming after classes introduced in ES6.
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);