Skip to main content

Command Palette

Search for a command to run...

JavaScript Concepts

Updated
•10 min read•View as Markdown

What is Node.js?

Node.js is an open-source JS runtime that allows you to execute JavaScript code on the server side. It’s built on Chrome's V8 JavaScript engine.

Runtime?

The environment where JavaScript code is executed. It could be

  1. On the server

  2. In the browser

  3. On a small watch

V8 engine?

The V8 engine is an open-source JavaScript engine developed by Google. It is used to execute JavaScript code in various environments, most notably in the Google Chrome web browser.

Mozilla has their own JS engine - SpiderMonkey

Safari - JavaScriptCore

Installing Node.js:

  • Build from source

  • Using a package manager (brew, chocolat)

  • Using nvm

If you’re on windows, download git bash at the very least

Starting a Node.js project:

To initialize a Node.js project locally,

  • Run the following command -
npm init -y
  • Exploring package.json

notion image

  • Writing some code
let firstName = "Harkirat Singh"
console.log(firstName)
  • Run the code
node index.js
  • Add a script in package.json
  "scripts": {
    "start": "node index.js"
  },
  • Run npm run start

npm

The full form of NPM is Node Package Manager.

It is a package manager for JavaScript, primarily used for managing libraries and dependencies in Node.js projects. NPM allows developers to easily install, update, and manage packages of reusable code.

Internal Package:

Node.js provides you some packages out of the box. Some common ones include

  1. fs - Filesystem

  2. path - Path related functions

  3. http - Create HTTP Servers (we’ll discuss this tomorrow)

External packages

These are packages written and maintained by other people. You just use their work in your project.

For example

  1. Express

  2. chalk

package-lock.json

The package-lock.json records the exact versions of all dependencies and their dependencies (sub-dependencies) that are installed at the time when npm install was run.

Q. Is it necessary to run npm init -y in Visual Studio Code when creating a folder or starting a new project?

Ans:

what npm init -y does:

  • Instantly creates a package.json file with default values.

  • This file tracks your project’s:

    • Name, version, and metadata

    • Installed dependencies (like Express)

    • Module type (CommonJS or ES module)

    • Scripts (like start or test)

Introduction to JS:

JavaScript is a lightweight, high-level programming language used to make web pages interactive. It runs in the browser for frontend tasks like form validation, animations, and dynamic content. With environments like Node.js, JavaScript can also run on the backend, allowing full-stack development using one language.

JavaScript is used both on the frontend and the backend. Some functions need to be defined and executed on the backend because they can't be done in the browser

For example:

Working with the file system using fs. If JavaScript running in the browser could read local files, it would create serious security issues, as developers or users could access sensitive data directly. That's why the browser does not allow direct file system access.

Originally, JavaScript only ran in the browser and couldn't run on the backend like Python or Rust. Node.js solved this problem by allowing JavaScript to run outside the browser, on the server side.

Features:

Javascript has the following -

1. Interpreted

JavaScript is an interpreted language, meaning it's executed line-by-line at runtime by the JavaScript engine in the browser or server environment, rather than being compiled into machine code beforehand.

notion image

Upsides -

  1. There is one less step to do before running your code

Downsides -

  1. Performance Overhead:

  2. More prone to runtime errors

2. Dynamically Typed

Variables in JavaScript are not bound to a specific data type. Types are determined at runtime and can change as the program executes

C++ Code (won’t compile)

#include <iostream>

int main() { 
  int a = 1;
  a = "hello";
  a = true;
}

JS Code (will compile)


var a = 1;
a = "harkirat";
a = true;

console.log(a)

3. Single threaded

JavaScript executes code in a single-threaded environment, meaning it processes one task at a time. We will dive deeper into this next week.

notion image

notion image

4. Garbage collected

JavaScript automatically manages memory allocation and deallocation through garbage collection, which helps prevent memory leaks by automatically reclaiming memory used by objects no longer in use.

notion image

Conclusion

Is JS a good language?

Yes and no. It is beginner friendly, but has a lot of performance overhead. Bun is trying to solve for a lot of this, but there’s a long way to go before JS can compete with languages like C++/Rust

Setting up environment:

  1. You can try all the code on github code space and also on vscode.

    Create folder on github→ Login to Github. Go to codespace. create codespace. vs code enviornment will open.

  2. Create an account on replit.

  3. Keep your browser console open for testing locally

Open your browser (Chrome, Firefox, Edge, etc.) → Right-click anywhere on the page and select: → "Inspect" → Then go to the "Console" tab → Type JavaScript code directly in the console

  1. Download node js and Make sure to check “Add to PATH” during installation

    Normally, JavaScript runs inside web browsers (like Chrome). Node.js lets you run JavaScript on your computer/server – like Python or Java.

How to Run a JavaScript File in VS Code:

  • Open VS Code

  • Go to File > Open Folder and select your project folder

  • Create a .js file (e.g., app.js)

  • Go to Terminal → New terminal

  • To run, in the terminal, type: node filename.js

  • Create folder → create js file → type code → view tab → terminal → go to inside folder where you kept all files → run file on terminal using node filename.js

Need some setting:

  1. view→ command palatte→ add dev container configuration files.→ show all defination → node js → rebuild now- > it will restart again with configuration.

Save all code and files to github:

  1. click on source control icon → click on “+” icon to add files which you want to commit → enter msg →click commit.

  2. click on three dots behind changes tab → click on push → so your data will push to github

After pushing all code you can download through zip file.

  1. once you done with coding you have to delete that machine from codespace

Syntax of Javascript:

1. Variables

Variables are used to store data. In JavaScript, you declare variables using var, let, or const.

❓ Why is var not used much now?

  1. var has function scope, not block scope — this can cause unexpected behavior.

  2. It allows redeclaration, which can lead to bugs.

  3. let and const are safer with block scope and better control.

Local variable:

-when we passed any parameter they act as local variable. -they will be inside function/block of code.

Global Variable:

-they will be within the code. or outside the block.

Example:

function sum(x,y){

s=x+y;

}

console.log(x); // it wont run because you print x ouside the block.

2. Data types

  1. Primitive (call by value): -string, Number, Boolean, Null, Undefined, symbol,BigInt

  2. Non Primitive (Call by reference): -Array, objects, Function

3. Operators

4. Functions

// Function declaration function

-Block of code that performs a specific task, can be invoked whenever needed.

  1. Function Defination:

    function function_name(){

    //do some code

    }

  2. Function Call:

    function_name();

  3. Pass the input:

    function function_name(par1,par2){

    //parameter

    //do some code

    }

    function_name("df"); //arguments

    Note:

    -when we pass input while defining function we called it - parameter

    -when we pass input while calling function we called it- arguments

5. If/Else

6. Loops

7. Memory:

  1. stack -Primitive- when u declare variable u get copy of it.

  2. Heap - Non primitive - when u declare variable u get change in original value.

8.String

  1. Index- when we take index whiile slicing it wont take

  2. last index. -slice can take - which will stat from end

  3. trim is used for to remove extra spaces

  4. strings in javascript is immutable.

//\n: to the next line

//\t: to tab space

a)Temperal literals

  • a way to have embedded expressions in string.

b)string interpolation- To create string by doing substitution of placeholder

Note: MDN web docs - to know more about string

//\n: to the next line

//\t: to tab space

Non-primitive Data Types:

  1. Objects

An object in JavaScript is a collection of key-value pairs, where each key is a string and each value can be any valid JavaScript data type, including another object.

eg.

-we can declare object by two ways: literal & constructor

-We can change objects values -we can freeze object

  1. Arrays

Arrays let you group data together

  1. its object type -collection of items

  2. they are mutable -Arrays are important data structures used in web development to store different types of data.

  3. Arrays are a better approach for storing multiple values compared to creating multiple variables

  4. Arrays in JavaScript can hold multiple values or items of different types.

  5. Arrays in JavaScript can be accessed by the length property.

  6. Arrays in JavaScript allow accessing values based on index.

  7. Arrays in JavaScript can be accessed by index and values can be changed.

  8. Arrays in JavaScript can be accessed using indexes starting from zero.

  9. Arrays in JavaScript have methods that allow us to change the array in place or return a new array.

  10. Arrays in JavaScript can be used to store and manipulate sets of values.

  11. Concatenating arrays in JavaScript using the concat() method.

  12. Deleting and adding elements in an array using indexes

  13. Arrays in JavaScript can be manipulated using the splice method.

  14. Removing and replacing elements in an array

Methods in array:

  1. push() - to add items at end

  2. pop() - to delete item from end

  3. toString() - converts array to string

  4. unshift - it will ad item at the start but all indecise will change

  5. shift - to remove value from array= we dont need to keep value.

  6. join = to merge all in one string

  7. slice & splice= in slice it will take some portion but not end index in splice it will remove taken portion

  8. trim = to remove spaces from start and end to check prototype go to google do inspect->console pass array and call it u will get prototype

push and concat problem -

  1. you can’t push second array in first array

  2. because that whole array will count as one element

  3. so to add two array we will use concat. alternatively we can use spread operator or flat operator.

Array of Objects

We can have more complex objects, for example an array of objects

Object of object

We can have an even more complex object (object of objects)

eg.

ForEach loop in Arrays:

  • arr.forEach(callBackFunction)

  • callback function: here it is a function to execute for each element in the array

  • a callback is a function passed as an argument to another function.

Syntax: arr.forEach((val) => { console.log(val); })

note: if we associate function with object or data structure then it turns out into method

Example:

to convert into uppercase:

console.log(val.toUpperCase());

Methods:

  1. Map:
  • create a new array wih the result of some operation. the value its callback returns are usd to form new array

Syntax: arr.map(callbackFnx(val,index,array))

ex.

you can store value of array in array. using value in array you can create new aray.

  1. Filter:
  • filtered value will stored in new array

eg.

  1. Reduce:
  • is used to reduce an array to a single value by applying a function to each element