DEV Community

jslovers for JSLovers

Posted on

JavaScript Basics: A Beginner’s Guide

JavaScript is one of the most widely used programming languages in the world, powering interactive and dynamic web applications. In this guide, we’ll explore the history of JavaScript, its core concepts like variables, conditions, loops, ECMAScript updates, and common methods for strings, arrays, and objects. Finally, we’ll walk through creating a simple "Hello World" application.


1. A Brief History of JavaScript

JavaScript was created in 1995 by Brendan Eich while working at Netscape. It was initially developed in just ten days and was first called Mocha, then LiveScript, and finally renamed JavaScript to capitalize on the popularity of Java at the time.

Key milestones in JavaScript’s evolution include:

  • 1997: ECMAScript (ES) was established as the standard for JavaScript.
  • 2009: ES5 introduced features like strict mode and JSON support.
  • 2015: ES6 (ECMAScript 2015) brought significant updates like let, const, arrow functions, template literals, and more.
  • Present: JavaScript continues to evolve with regular ECMAScript updates, making it more powerful and developer-friendly.

Today, JavaScript is used for both client-side and server-side development (e.g., Node.js) and is a cornerstone of modern web development.


2. Variables in JavaScript

Variables are used to store data that can be reused throughout your program. In JavaScript, you can declare variables using var, let, or const:

  • var: Function-scoped; can be redeclared.
  • let: Block-scoped; cannot be redeclared.
  • const: Block-scoped; immutable (value cannot be reassigned).

Example:

var name = "Alice";
let age = 30;
const country = "Canada";

console.log(name, age, country); // Output: Alice 30 Canada
Enter fullscreen mode Exit fullscreen mode

3. Conditional Statements

Conditional statements allow you to execute specific code blocks based on conditions.
Examples:

let temperature = 25;

// if-else statement
if (temperature > 30) {
    console.log("It's hot!");
} else {
    console.log("The weather is pleasant.");
}

// switch statement
let day = "Monday";
switch (day) {
    case "Monday":
        console.log("Start of the work week!");
        break;
    case "Friday":
        console.log("Weekend is near!");
        break;
    default:
        console.log("It's just another day.");
}
Enter fullscreen mode Exit fullscreen mode

4. Loops in JavaScript

Loops are used to repeat a block of code multiple times.
Examples:

// For loop
for (let i = 0; i < 3; i++) {
    console.log(i); // Output: 0, 1, 2
}

// While loop
let count = 0;
while (count < 3) {
    console.log(count); // Output: 0, 1, 2
    count++;
}

// For-of loop (useful for arrays)
const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
    console.log(fruit); // Output: apple, banana, cherry
}
Enter fullscreen mode Exit fullscreen mode

5. String Methods

Strings are sequences of characters. JavaScript provides many built-in methods to manipulate strings.
Examples:

let greeting = " Hello World! ";

// Convert to uppercase
console.log(greeting.toUpperCase()); // Output: " HELLO WORLD! "

// Remove whitespace from both ends
console.log(greeting.trim()); // Output: "Hello World!"

// Check if string includes a substring
console.log(greeting.includes("World")); // Output: true

// Extract part of the string
console.log(greeting.slice(1, 6)); // Output: "Hello"

// Replace part of the string
console.log(greeting.replace("World", "JavaScript")); // Output: " Hello JavaScript! "

Enter fullscreen mode Exit fullscreen mode

6. Array Methods

Arrays are used to store multiple values in a single variable. JavaScript offers numerous methods for working with arrays.
Examples:

const numbers = [1, 2, 3, 4];

// Add elements to the end
numbers.push(5);
console.log(numbers); // Output: [1, 2, 3, 4, 5]

// Remove the last element
numbers.pop();
console.log(numbers); // Output: [1, 2, 3, 4]

// Transform each element with map()
const squared = numbers.map(num => num * num);
console.log(squared); // Output: [1, 4, 9, 16]

// Filter elements based on condition
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]
Enter fullscreen mode Exit fullscreen mode

  1. Object Methods Objects store data as key-value pairs. Methods allow you to perform actions on objects. Examples:
const person = {
    firstName: "John",
    lastName: "Doe",
    age: 30,
    fullName() {
        return `${this.firstName} ${this.lastName}`;
    }
};

// Access properties
console.log(person.firstName); // Output: John

// Call method inside object
console.log(person.fullName()); // Output: John Doe

// Add new property dynamically
person.country = "USA";
console.log(person.country); // Output: USA

// Get keys and values of an object
console.log(Object.keys(person)); // Output: ["firstName", "lastName", "age", "fullName", "country"]
console.log(Object.values(person)); // Output: ["John", "Doe", 30, ƒ(), "USA"]
Enter fullscreen mode Exit fullscreen mode

8. ECMAScript Changes

JavaScript evolves through ECMAScript updates. Key changes include:
• ES6 (2015):
• Introduced let, const, arrow functions (=>), template literals (${}), destructuring ({}), default parameters.
• Added new data structures like Map and Set.
• ES7+:
• Features like async/await, optional chaining (?.), nullish coalescing (??), and array methods like .includes() enhance usability.
These updates make coding more efficient and expressive.


9. Creating a Hello World Application

The “Hello World” program is a classic way to start learning any programming language.
Code Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World</title>
</head>
<body>
    <h1>Welcome to JavaScript</h1>

    <script>
        // Display message in an alert box
        alert("Hello World!");

        // Write message to the document
        document.write("<p>Hello World!</p>");

        // Log message in the browser console
        console.log("Hello World!");
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Steps:

  1. Save this code as hello-world.html.
  2. Open it in any web browser.
  3. You’ll see an alert box with “Hello World!” followed by text on the page. By understanding these foundational concepts—variables, conditions, loops—and exploring methods for strings, arrays, and objects in JavaScript, you’re well-equipped to dive deeper into web development!

Top comments (0)