# Basic Javascript You Must Know

basic things you must know !!!

### **What is JavaScript?**

* A high-level, interpreted, multi-paradigm language (supports object-oriented & functional styles).
    
* It runs in the browser (client-side) but also on the server using Node.js.
    
* Conforms to the ECMAScript standard.
    

### **Why Learn JavaScript?**

* Powers all interactive web experiences.
    
* Foundation for frameworks like React, Angular, Vue.
    
* Can build full-stack apps (Node.js), mobile (React Native), and desktop apps (Electron).
    

Setup:

* Use VS Code with the Live Server extension for instant reload.
    
* Write code in separate .js files linked via &lt;script src="main.js"&gt;&lt;/script&gt;.
    

Output Basics:

* alert("Hello") → not recommended for debugging.
    
* Use console.log(), console.warn(), console.error().
    
* Open browser Developer Tools → Console.
    

### **Variables:**

* Use let and const (avoid var).
    
* let allows reassignment; const doesn’t.
    
* Example:
    
* js
    

const name = "John";

let score = 10;

score = 20;

### **Data Types:**

* Primitive: String, Number, Boolean, Null, Undefined, Symbol.
    
* Objects: Arrays, Object Literals, Functions.
    
* Check type: typeof variable.
    

---

## **🚀 Part 2: Core Syntax & Logic Essentials**

### **Strings:**

* Use Backticks \` (template literals):
    
* js
    

console.log(\`My name is ${name}\`);

* Methods: .length, .toUpperCase(), .split(', ').
    

### **Arrays:**

* Create: const fruits = \['apple', 'orange'\];
    
* Add/Remove: .push(), .unshift(), .pop()
    
* Check: Array.isArray(fruits)
    
* Find index: .indexOf('orange').
    

### **Objects:**

* Key-value pairs:
    
* js
    

const person = {

  name: 'John',

  age: 30,

  hobbies: \['music', 'sports'\],

  address: { city: 'Boston' }

};

* Access: [**person.address.city**](http://person.address.city/)
    
* Destructure:
    
* js
    

const { name, age } = person;

### **JSON:**

* Convert:
    
* js
    

JSON.stringify(object)

JSON.parse(jsonString)

### **Loops:**

* For loop:
    
* js
    

for (let i = 0; i &lt; 10; i++) console.log(i);

* For...of loop: for (let item of items).
    
* Higher-order methods:
    
    * .forEach() → iterate.
        
    * .map() → transform.
        
    * .filter() → filter results.
        

### **Conditionals:**

* if, else if, else
    
* Equality: === (strict), == (loose).
    
* Logical operators: && (and), || (or).
    
* Ternary:
    
* js
    

const color = x &gt; 10 ? 'red' : 'blue';

## **🧩 Functions**

* Functions are reusable blocks of code that perform specific tasks.
    
* Declared using the function keyword:
    
* js
    

function greet(name) {

  console.log(\`Hello ${name}\`);

}

greet('John');

* Can return values using return.
    
* Functions may have default parameters:
    
* js
    

function add(a = 1, b = 1) {

  return a + b;

}

---

## **🌀 Arrow Functions (ES6)**

*Introduced in ES6 for shorter syntax and lexical this.*

* Example comparison:
    
* js
    

*// Regular*

function add(x, y) { return x + y; }

*// Arrow*

const add = (x, y) =&gt; x + y;

* If only one statement → implicit return; no curly braces or return.
    
* For a single parameter, parentheses are optional.
    
* Arrow functions don’t rebind their own this — they borrow it lexically (from their defining scope).
    

---

## **🏗️ Constructor Functions & Prototypes (ES5‑style OOP)**

Before classes, JavaScript used constructor functions with this and prototype.

js

function Person(firstName, lastName, dob) {

  this.firstName = firstName;

  this.lastName  = lastName;

  this.dob = new Date(dob);

}

Add shared methods to the prototype — more memory efficient than defining them inside each instance:

js

Person.prototype.getFullName = function () {

  return `${this.firstName} ${this.lastName}`;

};

Create an object:

js

const person1 = new Person('John', 'Doe', '4‑03‑1990');

console.log(person1.getFullName());

---

## **🧱 ES6 Classes**

ES6 introduced class syntax for cleaner OOP structure (built on prototypes).

js

class Person {

  constructor(firstName, lastName, dob) {

    this.firstName = firstName;

    this.lastName  = lastName;

    this.dob = new Date(dob);

  }

  getFullName() {

    return `${this.firstName} ${this.lastName}`;

  }

}

* Create instances with new Person().
    
* You can extend classes to inherit behavior:
    
* js
    

class Employee extends Person {

  constructor(firstName, lastName, job) {

    super(firstName, lastName);

    this.job = job;

  }

}

---

## **🪟 Window Object & DOM**

* The window object represents the browser environment.
    
* Access global functions, alerts, timers:
    
* js
    

window.alert('Hi');

console.log(window.innerWidth);

* The document object represents the HTML loaded in the browser.
    

---

## **🌳 DOM Selection**

Selecting HTML elements via JavaScript methods:

js

document.getElementById('my-id');

document.querySelector('.class-name');

document.querySelectorAll('p');

document.getElementsByClassName('demo');

* querySelector → first match.
    
* querySelectorAll → NodeList (similar to array).
    

---

## **🎨 Manipulating the DOM**

Change content/styles:

js

const title = document.querySelector('h1');

title.textContent = 'Hello JS';

[**title.style**](http://title.style/).color = 'blue';

Add or remove elements:

js

const ul = document.querySelector('.items');

ul.remove();

ul.lastElementChild.textContent = 'Updated Item';

---

## **⚙️ Events**

Listen and handle user actions:

js

const btn = document.querySelector('.btn');

btn.addEventListener('click', (e) =&gt; {

  e.preventDefault();

  console.log('Button Clicked');

});

Event types include click, mouseover, submit, keydown.

* e.preventDefault() stops default browser behavior.
    

---

## **🧾 Form Script**

Handle form submission and validation:

js

const form = document.querySelector('#my-form');

const nameInput = document.querySelector('#name');

form.addEventListener('submit', (e) =&gt; {

  e.preventDefault();

  if (nameInput.value === '') {

    alert('Please fill the field');

  } else {

    console.log('Success:', nameInput.value);

  }

});
