Appearance
JavaScript Basics
JavaScript uses a C-style syntax (like Java and C++), but its underlying model is quite different. It’s a prototype-based object-oriented language with strong functional programming roots. Like Python, JavaScript uses dynamic types and is considered loosely typed, meaning variables can change type and implicit type conversion (coercion) is common.
Console Output
Use console.log(...) to "print" to the console, similar to statements in other languages like std::cout in C++ and print in Python.
js
console.log('Hello!');Syntax
Semicolon line endings are optional but recommended for clarity. The Prettier code formatting plugin will automatically add semicolons to your code.
Curly brackets { ... } are used to define blocks of code, just like in C++. These blocks are used in functions, loops, conditionals, and other control structures.
Indentation is for clarity and is recommended to make your code more readable. The Prettier code formatting plugin will automatically handle indentation for you.
Control Structures
JavaScript supports familiar C/C++/Java style control structures, including if, then, else, for, while, switch, and the ternary operator A ? B : C.
The if statement executes a block of code if a specified condition is true.
js
let number = 10;
if (number > 5) {
console.log('greater than 5');
} else {
console.log('5 or less');
}The ternary operator is a shorthand for the if-else statement.
js
let number = 10;
let result = (number > 5) ? 'greater than 5' : '5 or less';
console.log(result);The switch statement behaves similarly to C++ and Java. However, unlike C++, JavaScript allows the switch value and case labels to be any type, not just integers or enums.
js
let fruit = 'apple';
switch (fruit) {
case 'apple':
console.log('It’s an apple!');
break;
case 'banana':
console.log('It’s a banana!');
break;
default:
console.log('Unknown fruit');
}Don`t forget the break statement to avoid fall-through (just like in C++).
Boolean Operators
JavaScript provides standard boolean operators similar to C++ and Java:
js
// AND operator (&&)
let a = true && true; // true
let b = true && false; // false
// OR operator (||)
let c = true || false; // true
let d = false || false; // false
// NOT operator (!)
let e = !true; // false
let f = !false; // true
// You can combine operators
let g = (true && false) || (!false); // trueComparison Operators
JavaScript includes standard comparison operators that return boolean values:
js
// Equal (==) and Not Equal (!=)
let a = 5 == 5; // true
let b = 5 != 3; // true
// Strict Equal (===) and Strict Not Equal (!==)
let c = 5 === 5; // true
let d = 5 !== "5"; // true
// Greater Than (>) and Less Than (<)
let e = 5 > 3; // true
let f = 3 < 5; // true
// Greater Than or Equal (>=) and Less Than or Equal (<=)
let g = 5 >= 5; // true
let h = 3 <= 2; // falseExternal Resources