Fundamentals for Node JS

Create a file

Create a file named basics.js.

Open terminal.


How to Use Variables and Functions

var a = 10; // function scope variable
let b = 20; // block scope variable
const c = 30;

a = 100;
b = 200;
// c = 300; // this will give an error because const value cannot be changed

console.log(a + b + c);


To run and check output in terminal:

node basics.js

You can redeclare and reassign var and let values.

You cannot change a const value — this will give an error.


How to Use Conditions and Loops

if (a == 200) {
console.log("this is if condition");
} else {
console.log("this is else condition");
}


Function Example

function fruit(item) {
console.log("fruit is " + item);
}

fruit("apple");
fruit("banana");


For Loop

for (var a = 0; a <= 10; a++) {
console.log(a);
}


While Loop

var a = 0;
while (a <= 10) {
console.log(a);
a++;
}


How to Use Arrays and Objects

Array Example

var user = ["anil", "sam", "peter", "bruce"];

for (var a = 0; a < user.length; a++) {
console.log(user[a]);
}


Object Example

var user = {
name: "anil",
city: "delhi",
age: 29,
};

console.log(user.name);
console.log(user.city);
console.log(user.age);


How to Import Functions or Variables From Another File

Export from data.js:

module.exports = {
userName: "Anil Sidhu",
};


Import in basics.js:

const data = require("./data.js");

console.log(data.userName);