Hello World Program in JavaScript
javascript
*// Create a file in Visual Studio Code with .js extension* console.log("Hello World");
To run:
- Open terminal at file location
- Run:
node filename.js(make sure Node.js is installed and set in system variables)
Output:
Hello World
Comments in JavaScript
javascript
// This is a single line comment
/*This is a multi-line comment */
Comments don't impact execution.
Variables in JavaScript
JavaScript variables are loosely typed - no explicit data types are needed.
Example of declaring a variable:
let a = 4;
console.log(a);
// Prints: 4
To check type of variable:
console.log(typeof a); // Outputs: "number"
Variables can be declared with var, let, and const. let and const were introduced in ES6.
var, let, const
var: Function scoped, can be redeclared and reassigned.let: Block scoped, cannot be redeclared, but can be reassigned.const: Block scoped, cannot be redeclared or reassigned (constant).
Example:
let a = 4; a = 5; // OK
let a=6; // cannot be redeclared
const b = 10; b = 15; // Error: Assignment to constant variable.
var c = 7; var c = 8; // Allowed with var` ,can be redeclared and reassigned.
Use let or const instead of var for better scoping.
Boolean negation operator
let flag = true;
console.log(!flag); *// Prints: false*
Negation ! works only with boolean values.
Reassignment and variable declaration
`javascript
let c = a + b; // Declared once c = a + b; // Reassignment allowed without let keyword
let c = a + b; // Error: 'c' already declared`
Loops in JavaScript
while loop
let i = 0;
while (i < 10)
{
console.log(i);
i++;
}
Infinite loop caution: Condition must eventually become false.
- The loop starts with
i = 0. - Each iteration prints
iand increases it by 1. - When
ireaches 10, the condition(i < 10)becomes false, so the loop stops.
If you forget to update i, the condition never becomes false, creating an infinite loop.
do-while loop
javascript
let i = 10;
do
{
console.log(i);
i++;
} while (i < 10);
Executes once before checking condition.
for loop
for (let i = 0; i <= 10; i++)
{
console.log(i);
}
Use when the number of iterations is known.
Example: Find multiples of 2 and 5
for (let k = 1; k <= 10; k++)
{
if (k % 2 === 0 && k % 5 === 0)
{
console.log(k);
}
} *// Output: 10*
break statement example
let n = 0;
for (let k = 1; k <= 100; k++)
{
if (k % 2 === 0 && k % 5 === 0)
{
n++;
console.log(k);
if (n === 3)
break;
// Stop after first 3 matches*
}
}
- The loop runs from
k = 1tok = 100. - Inside, the condition
(k % 2 === 0 && k % 5 === 0)checks whetherkis divisible by both 2 and 5 (which means divisible by 10). - Each valid match increases
nby 1 and printsk. - Once
nreaches 3, thebreakstatement exits the loop early.
So the output stops after printing the first 3 such numbers (10, 20, 30).
Arrays in JavaScript
Declaring and initializing an array
javascript
let marks = new Array(6);
marks = [20, 40, 35, 45, 50, 37];
Or simply:
javascript
let marks = [20, 40, 35, 45, 50, 37];
Accessing array elements
javascript
console.log(marks[2]); // Outputs: 35*
Updating array element
javascript
marks[3] = 14; // Change fourth element to 14
console.log(marks);
Array length
javascript
console.log(marks.length); // Outputs: 6
Adding/removing elements
javascript
marks.push(65); // Add 65 at the end* marks.pop(); // Removes last element marks.unshift(12); // Add 12 at beginning*
Array methods: indexOf, includes, slice
javascript
console.log(marks.indexOf(35)); // Get index of 35* console.log(marks.includes(120)); // false - if 120 not found
let subMarks = marks.slice(2, 5); // elements from index 2 to 4
Loop to sum array elements
javascript
let sum = 0;
for(let i = 0; i < marks.length; i++)
{
sum += marks[i];
}
console.log(sum);
Using reduce
javascript
let totalMarks = marks.reduce((sum, mark) => sum + mark, 0);
console.log(totalMarks);
Filtering even numbers from an array
javascript
let scores = [12, 13, 14, 16];
let evenScores = [];
for(let i = 0; i < scores.length; i++)
{
if(scores[i] % 2 === 0)
{
evenScores.push(scores[i]);
}
}
console.log(evenScores); *// [12, 14, 16]*
Using filter method
javascript
let evenScores = scores.filter(score => score % 2 === 0);
console.log(evenScores);
Mapping over array elements
Multiply evens by 3:
javascript
let mappedScores = evenScores.map(score => score * 3);
console.log(mappedScores);
Combining filter, map, reduce
`javascript
let result = scores .filter(score => score % 2 === 0) .map(score => score * 3) .reduce((total, score) => total + score, 0);
console.log(result);
Sorting
Sorting strings
javascript
let fruits = ['Banana', 'Mango', 'Apple'];
fruits.sort();
console.log(fruits);
Sorting numbers (with custom comparator)
`javascript
let numbers = [12, 3, 19, 16, 14];
numbers.sort((a, b) => a - b);
console.log(numbers); // Ascending order
numbers.sort((a, b) => b - a);
console.log(numbers); // Descending order`
Functions in JavaScript
Named function
function add(a, b)
{
return a + b;
}
let result = add(2, 3);
console.log(result); // 5
Anonymous function assigned to variable
let add = function(a, b)
{
return a + b;
};
console.log(add(2, 3)); // 5
Arrow function (ES6)
let add = (a, b) => a + b;
console.log(add(2, 3)); // 5
Variable scope differences: var vs let vs const
varis function scopedletandconstare block scoped
Example problem with var:
`javascript
if (true) {
var grade = "Afternoon"; // var scoped outside block
}
console.log(grade); // Prints "Afternoon"
if (true)
{
let grade = "Evening";
// let scoped inside block
}
console.log(grade); // Error if grade not declared outside block`
Strings in JavaScript
javascript
let day = "Tuesday";
console.log(day.length); // String length
// Substring with slice
let sub = day.slice(0, 4); // 'Tues'// Access character by index
console.log(day[1]); // 'u'// Split string
let parts = day.split('s'); // splits at 's'// Trim whitespace
let rawString = " hello ";
console.log(rawString.trim()); // 'hello'
Converting string to number and vice versa
javascript
let str = "27";
let num = parseInt(str);
console.log(num - 23); // Subtract numbers correctly
console.log(num.toString()); // Convert back to string*
Objects in JavaScript
`javascript
let person = { firstName: "John", lastName: "Doe", gender: "Male" };
// Access properties
console.log(person.firstName);
console.log(person['lastName']);
// Update property
person.firstName = "Tim";
// Add new property
person.age = 30;
// Delete property
delete person.gender;
// Check if property exists
console.log('gender' in person); // false after deletion
// Iterate properties
for (let key in person)
{
console.log(key + ": " + person[key]);
}
Object methods (functions as properties)
javascript
let person = {
firstName: "Tim",
lastName: "Smith",
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
console.log(person.fullName()); // Call function property
Classes in JavaScript (ES6)
javascript
class Person {
constructor(firstName, lastName) {
this.firstName = firstName; // instance variable
this.lastName = lastName; // instance variable
}
fullName() {
return this.firstName + " " + this.lastName;
}
get location() {
return "Canada"; // getter property
}
}
// Create instance
const p1 = new Person("Tim", "Joseph");
console.log(p1.fullName());
console.log(p1.location);
Exporting and importing classes in Node.js
Export class:
javascript
module.exports = Person;
Import and use in another file:
javascript
const Person = require('./Person');
const p1 = new Person("Chris", "Edward");
console.log(p1.fullName());
0 Comments