DEV Community

Cover image for Javascript important concepte || important javascript concepte
Anil
Anil

Posted on

Javascript important concepte || important javascript concepte

step by step with code examples to help you understand each concept better.


1. JS Introduction

JavaScript is a versatile language that runs in the browser or on the server (with Node.js). It's used to make web pages interactive.

<!DOCTYPE html>
<html>
<body>
  <h2>Hello, JavaScript!</h2>
  <button onclick="myFunction()">Click Me</button>

  <script>
    function myFunction() {
      alert("Hello, welcome to JavaScript!");
    }
  </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

2. JS Where To

JavaScript can be placed in three locations:

  1. Inline:
<button onclick="alert('Inline JS')">Click me</button>
Enter fullscreen mode Exit fullscreen mode
  1. Internal (inside a <script> tag):
<script>
  function showMessage() {
    alert("Internal JS");
  }
</script>
Enter fullscreen mode Exit fullscreen mode
  1. External (in an external .js file):
<!-- index.html -->
<script src="script.js"></script>

<!-- script.js -->
console.log("This is external JS!");
Enter fullscreen mode Exit fullscreen mode

3. JS Output

Different ways to display output in JavaScript:

<!-- HTML output -->
<p id="output"></p>

<script>
  // Write into HTML element
  document.getElementById("output").innerHTML = "Hello World!";

  // Write into browser's console
  console.log("Console Output");

  // Display in an alert box
  alert("Alert Box");
</script>
Enter fullscreen mode Exit fullscreen mode

4. JS Statements

A statement is an instruction. For example:

let a = 5;    // This is a statement
let b = 6;    // This is another statement
let sum = a + b;  // Statement calculating the sum
Enter fullscreen mode Exit fullscreen mode

5. JS Syntax

Syntax refers to the set of rules on how JavaScript programs are constructed:

let name = "John";  // Variable declaration and assignment
console.log(name);  // Statement to output the value of 'name'
Enter fullscreen mode Exit fullscreen mode

6. JS Comments

// This is a single-line comment

/* 
   This is a 
   multi-line comment
*/

let x = 10; // This is an inline comment
Enter fullscreen mode Exit fullscreen mode

7. JS Variables

Variables store data values. You can declare them using let, var, or const.

let name = "Alice";   // Declaring a string variable
var age = 30;         // Declaring a number variable
const country = "USA"; // Declaring a constant
Enter fullscreen mode Exit fullscreen mode

8. JS Let

The let keyword allows you to declare variables with block scope.

let x = 10;
if (x > 5) {
  let y = 20; // 'y' only exists inside this block
}
console.log(y); // Error: y is not defined
Enter fullscreen mode Exit fullscreen mode

9. JS Const

Variables declared with const are immutable (you cannot reassign them).

const PI = 3.14159;
PI = 3.14; // Error: Assignment to constant variable.
Enter fullscreen mode Exit fullscreen mode

10. JS Operators

Operators are used to perform operations on variables and values:

let a = 10;
let b = 20;

let sum = a + b;  // Arithmetic operator
let isEqual = (a == b);  // Comparison operator
let notEqual = (a != b);  // Logical operator
Enter fullscreen mode Exit fullscreen mode

11. JS Arithmetic

JavaScript provides basic arithmetic operators:

let x = 5;
let y = 2;

let sum = x + y;  // Addition
let difference = x - y;  // Subtraction
let product = x * y;  // Multiplication
let quotient = x / y;  // Division
let remainder = x % y;  // Modulus (remainder of division)
Enter fullscreen mode Exit fullscreen mode

12. JS Assignment

Assignment operators assign values:

let x = 10;  // Assign 10 to x
x += 5;  // Add 5 to x (x = x + 5)
x *= 2;  // Multiply x by 2
Enter fullscreen mode Exit fullscreen mode

13. JS Data Types

JavaScript has various data types:

let name = "Alice";  // String
let age = 25;        // Number
let isStudent = true; // Boolean
let person = {name: "John", age: 30}; // Object
let colors = ["Red", "Blue", "Green"]; // Array
let notDefined; // Undefined
let emptyValue = null; // Null
Enter fullscreen mode Exit fullscreen mode

14. JS Functions

Functions are blocks of code designed to perform tasks.

function greet(name) {
  return "Hello " + name;
}

console.log(greet("Alice"));  // Output: Hello Alice
Enter fullscreen mode Exit fullscreen mode

15. JS Objects

JavaScript objects are key-value pairs.

let person = {
  name: "John",
  age: 30,
  greet: function() {
    console.log("Hello, " + this.name);
  }
};

person.greet();  // Output: Hello, John
Enter fullscreen mode Exit fullscreen mode

16. JS Object Properties

Access object properties using dot notation or bracket notation:

let car = {make: "Toyota", model: "Corolla"};
console.log(car.make);  // Output: Toyota
console.log(car["model"]);  // Output: Corolla
Enter fullscreen mode Exit fullscreen mode

17. JS Object Methods

Object methods are functions stored as object properties:

let person = {
  name: "Alice",
  sayHello: function() {
    return "Hello, " + this.name;
  }
};

console.log(person.sayHello());  // Output: Hello, Alice
Enter fullscreen mode Exit fullscreen mode

18. JS Object Constructors

Object constructors allow you to create multiple objects with the same structure:

function Person(name, age) {
  this.name = name;
  this.age = age;
}

let john = new Person("John", 30);
console.log(john.name);  // Output: John
Enter fullscreen mode Exit fullscreen mode

These are the first few examples of JavaScript fundamentals with explanations and code. Let me know if you'd like to dive deeper into specific sections like arrays, loops, string manipulation, etc.!

Let’s continue with the full list of JavaScript concepts step by step, along with code examples:


19. JS Events

JavaScript can respond to various user events like clicks, mouse movements, or key presses.

<button onclick="displayMessage()">Click Me</button>

<script>
  function displayMessage() {
    alert("Button clicked!");
  }
</script>
Enter fullscreen mode Exit fullscreen mode

20. JS Strings

Strings in JavaScript are sequences of characters.

let greeting = "Hello, World!";
let length = greeting.length;  // String length
let upperCaseGreeting = greeting.toUpperCase(); // Convert to uppercase
console.log(upperCaseGreeting);  // Output: HELLO, WORLD!
Enter fullscreen mode Exit fullscreen mode

21. JS String Methods

JavaScript provides several built-in string methods:

let str = "Hello, World!";
let subStr = str.substring(0, 5);  // Extract substring
let replacedStr = str.replace("World", "Everyone");  // Replace part of string
console.log(replacedStr);  // Output: Hello, Everyone!
Enter fullscreen mode Exit fullscreen mode

22. JS String Search

You can search for substrings in JavaScript strings:

let sentence = "JavaScript is awesome!";
let position = sentence.indexOf("awesome");  // Finds the position of the word 'awesome'
console.log(position);  // Output: 15
Enter fullscreen mode Exit fullscreen mode

23. JS String Templates

Template literals allow embedding variables and expressions in strings.

let name = "Alice";
let greeting = `Hello, ${name}!`;  // Template literal using backticks
console.log(greeting);  // Output: Hello, Alice!
Enter fullscreen mode Exit fullscreen mode

24. JS Numbers

JavaScript handles integers and floating-point numbers.

let num1 = 5;
let num2 = 2.5;
let sum = num1 + num2;  // Adding numbers
console.log(sum);  // Output: 7.5
Enter fullscreen mode Exit fullscreen mode

25. JS BigInt

BigInt is used for arbitrarily large integers.

let bigNumber = BigInt("123456789012345678901234567890");
console.log(bigNumber);  // Output: 123456789012345678901234567890n
Enter fullscreen mode Exit fullscreen mode

26. JS Number Methods

JavaScript provides methods for numbers like:

let num = 9.656;
let rounded = num.toFixed(2);  // Rounds to 2 decimal places
console.log(rounded);  // Output: 9.66
Enter fullscreen mode Exit fullscreen mode

27. JS Number Properties

JavaScript has built-in number properties:

let max = Number.MAX_VALUE;  // Largest possible number in JS
console.log(max);  // Output: 1.7976931348623157e+308
Enter fullscreen mode Exit fullscreen mode

28. JS Arrays

Arrays are lists of values:

let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[1]);  // Output: Banana
Enter fullscreen mode Exit fullscreen mode

29. JS Array Methods

JavaScript arrays come with various methods:

let fruits = ["Apple", "Banana", "Cherry"];
fruits.push("Mango");  // Adds an element at the end
let lastFruit = fruits.pop();  // Removes the last element
console.log(lastFruit);  // Output: Mango
Enter fullscreen mode Exit fullscreen mode

30. JS Array Search

You can search for values in arrays:

let numbers = [1, 2, 3, 4, 5];
let index = numbers.indexOf(3);  // Find the index of 3
console.log(index);  // Output: 2
Enter fullscreen mode Exit fullscreen mode

31. JS Array Sort

You can sort arrays using sort():

let fruits = ["Banana", "Apple", "Cherry"];
fruits.sort();  // Sort alphabetically
console.log(fruits);  // Output: ["Apple", "Banana", "Cherry"]
Enter fullscreen mode Exit fullscreen mode

32. JS Array Iteration

Use loops or array methods to iterate through elements:

let fruits = ["Apple", "Banana", "Cherry"];
fruits.forEach((fruit) => console.log(fruit));  // Output each fruit
Enter fullscreen mode Exit fullscreen mode

33. JS Array Const

Arrays declared with const can still have their contents modified:

const fruits = ["Apple", "Banana"];
fruits.push("Cherry");  // This works
console.log(fruits);  // Output: ["Apple", "Banana", "Cherry"]
Enter fullscreen mode Exit fullscreen mode

34. JS Dates

JavaScript provides the Date object to work with dates:

let date = new Date();
console.log(date);  // Output: Current date and time
Enter fullscreen mode Exit fullscreen mode

35. JS Date Formats

You can format the date in different ways:

let date = new Date();
console.log(date.toDateString());  // Output: Mon Sep 28 2024
Enter fullscreen mode Exit fullscreen mode

36. JS Date Get Methods

JavaScript provides methods to get parts of a date:

let date = new Date();
let year = date.getFullYear();  // Get the year
let month = date.getMonth();  // Get the month (0-11)
console.log(year, month);  // Output: 2024, 8 (September)
Enter fullscreen mode Exit fullscreen mode

37. JS Date Set Methods

You can set specific parts of a date:

let date = new Date();
date.setFullYear(2025);  // Set the year to 2025
console.log(date);  // Output: Updated date with the new year
Enter fullscreen mode Exit fullscreen mode

38. JS Math

JavaScript provides a Math object for mathematical operations:

let x = Math.PI;  // Value of PI
let y = Math.sqrt(16);  // Square root of 16
console.log(x, y);  // Output: 3.141592653589793, 4
Enter fullscreen mode Exit fullscreen mode

39. JS Random

You can generate random numbers in JavaScript:

let randomNum = Math.random();  // Generates a number between 0 and 1
console.log(randomNum);
Enter fullscreen mode Exit fullscreen mode

40. JS Booleans

Booleans can have two values: true or false.

let isJavaScriptFun = true;
let isFishTasty = false;
console.log(isJavaScriptFun);  // Output: true
Enter fullscreen mode Exit fullscreen mode

41. JS Comparisons

Comparison operators are used to compare values:

let a = 10;
let b = 5;
console.log(a > b);  // true
console.log(a == b);  // false
console.log(a !== b);  // true
Enter fullscreen mode Exit fullscreen mode

42. JS If Else

Conditional statements allow you to execute code based on conditions:

let age = 18;
if (age >= 18) {
  console.log("You are an adult.");
} else {
  console.log("You are not an adult.");
}
Enter fullscreen mode Exit fullscreen mode

43. JS Switch

The switch statement allows you to execute different blocks of code based on a value:

let fruit = "Apple";

switch (fruit) {
  case "Banana":
    console.log("Banana");
    break;
  case "Apple":
    console.log("Apple");
    break;
  default:
    console.log("Unknown fruit");
}
Enter fullscreen mode Exit fullscreen mode

44. JS Loop For

The for loop allows you to repeat code a specified number of times:

for (let i = 0; i < 5; i++) {
  console.log(i);  // Output: 0, 1, 2, 3, 4
}
Enter fullscreen mode Exit fullscreen mode

45. JS Loop For In

The for-in loop iterates over properties of an object:

let person = {name: "John", age: 30, city: "New York"};
for (let key in person) {
  console.log(key + ": " + person[key]);
}
Enter fullscreen mode Exit fullscreen mode

46. JS Loop For Of

The for-of loop is used to iterate over iterable objects like arrays:

let fruits = ["Apple", "Banana", "Cherry"];
for (let fruit of fruits) {
  console.log(fruit);  // Output each fruit
}
Enter fullscreen mode Exit fullscreen mode

47. JS Loop While

The while loop executes as long as the condition is true:

let i = 0;
while (i < 5) {
  console.log(i);  // Output: 0, 1, 2, 3, 4
  i++;
}
Enter fullscreen mode Exit fullscreen mode

48. JS Break

break is used to exit a loop:

for (let i = 0; i < 5; i++) {
  if (i === 3) break;
  console.log(i);  // Output: 0, 1, 2
}
Enter fullscreen mode Exit fullscreen mode

49. JS Iterables

Objects that can be iterated over are called iterables, like arrays, strings, maps, etc.

let str = "Hello";
for (let char of str) {
  console.log(char);  // Output each character
}
Enter fullscreen mode Exit fullscreen mode

This is the continuation of the JavaScript tutorial, covering the next set of concepts. Let me know if you'd like further

details or any clarification!

Top comments (0)