Origins of JavaScript
Before we go into basics of JavaScript, we have look at
the stunning websites that were made using JS.
JavaScript was created in 1995 by Brendan Eich while working at Netscape Communications. Initially, the language was developed to allow websites to become dynamic, evolving from the static HTML pages of the early web. JavaScript's primary purpose was to create interactive web elements like form validation, animations, and basic web behavior.
At the time, the web was dominated by two browsers: Netscape Navigator and Microsoft's Internet Explorer. JavaScript was developed under the name **Mocha**, later renamed **LiveScript**, and eventually settled as **JavaScript**. Its early development was rushed due to the browser wars between Netscape and Microsoft, which led to some early shortcomings and limitations.
JavaScript, however, gained widespread adoption because of its ability to run directly in web browsers without the need for server interaction. In 1997, JavaScript was standardized under the **ECMAScript** specification to ensure consistency across different browsers. ECMAScript continues to be updated with new features, and JavaScript remains one of the most widely used programming languages today.
Programming in JavaScript: Then and Now
Early JavaScript programming involved adding small scripts directly into HTML documents to control behavior. For example, you might create a form validation script that checked if users filled in the required fields. However, as web applications became more complex, so did JavaScript.
Early developers faced challenges due to inconsistencies between browsers and the lack of powerful features. But over time, JavaScript evolved into a fully-fledged programming language capable of handling complex operations both in the browser (client-side) and, with the advent of Node.js, on the server (server-side).
Modern JavaScript now features improved syntax (e.g., ES6 features like arrow functions, classes, promises), better error handling, and a rich ecosystem of libraries and frameworks (like **React.js**, **Angular.js**, and **Vue.js**) that simplify application development.
Basics of JavaScript
Before diving into complex topics, let's discuss the fundamental building blocks of JavaScript. These include variables, data types, operators, conditionals, loops, and functions.
1. Variables
Variables are containers for storing data values. In JavaScript, you can define variables using `var`, `let`, or `const`.
```javascript
var name = "John"; // Using var (old way)
let age = 25; // Using let (modern way)
const PI = 3.14; // Constant value
```
- `var` is function-scoped and can be re-assigned.
- `let` is block-scoped and modern JavaScript's preferred variable declaration.
- `const` declares a block-scoped constant variable, which cannot be re-assigned after its initialization.
2. Data Types
JavaScript has several basic data types, including:
- **String**: `"Hello"`
- **Number**: `123`
- **Boolean**: `true` or `false`
- **Object**: `{key: value}`
- **Array**: `[1, 2, 3]`
- **Null**: `null`
- **Undefined**: `undefined`
```javascript
let name = "Alice"; // String
let age = 30; // Number
let isStudent = false; // Boolean
let user = {name: "John", age: 25}; // Object
let colors = ["red", "green", "blue"]; // Array
```
3. Operators
JavaScript supports various operators, including arithmetic, comparison, and logical operators.
- **Arithmetic Operators**: `+`, `-`, `*`, `/`
- **Comparison Operators**: `==`, `===`, `!=`, `<`, `>`, etc.
- **Logical Operators**: `&&` (AND), `||` (OR), `!` (NOT)
```javascript
let sum = 5 + 3; // 8
let isEqual = 5 == "5"; // true (loose equality)
let isStrictEqual = 5 === "5"; // false (strict equality)
let andOperator = true && false; // false
```
4. Conditionals
Conditional statements in JavaScript allow you to control the flow of the program based on certain conditions.
```javascript
if (age > 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
```
You can also use the ternary operator for shorthand conditionals:
```javascript
let message = age > 18 ? "Adult" : "Minor";
```
5. Loops
JavaScript loops enable you to repeat code execution based on certain conditions.
- **for loop**:
```javascript
for (let i = 0; i < 5; i++) {
console.log(i);
}
```
- **while loop**:
```javascript
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
```
6. Functions
Functions allow you to encapsulate reusable pieces of code.
```javascript
function greet(name) {
return "Hello, " + name;
}
console.log(greet("Alice")); // "Hello, Alice"
```
You can also use **arrow functions** (introduced in ES6):
```javascript
const greet = (name) => `Hello, ${name}`;
```
Programming in JavaScript
To begin programming in JavaScript, you need an environment to write, run, and test your code. JavaScript can run in any web browser, but for modern development, most developers use specialized tools and editors. Here's a step-by-step guide on setting up your JavaScript environment:
1. Install a Code Editor
A code editor is necessary for writing JavaScript. Popular options include:
- **Visual Studio Code**: Highly popular with JavaScript developers for its rich extensions and debugging support.
- **Sublime Text**: Lightweight and fast, with JavaScript support.
- **Atom**: Open-source editor with a focus on collaboration.
2. https://reactjsexample.com/tag/hackathon/(Optional for Server-Side Development)
If you're interested in developing back-end or full-stack applications, installing **Node.js** allows you to run JavaScript on your local machine without a browser. Node.js also comes with **npm** (Node Package Manager), which lets you install libraries and frameworks.
3. Browser Developer Tools
All modern browsers come with developer tools that include a **JavaScript console** for running scripts directly. You can open it by pressing `F12` or right-clicking a webpage and selecting **Inspect** > **Console**.
### Vanilla JavaScript vs. Angular.js
**Vanilla JavaScript** refers to using plain JavaScript without any additional libraries or frameworks. It's the foundational language and is often used for building small applications or learning core concepts.
```html
<!DOCTYPE html>
<html>
<head>
<title>Vanilla JS Example</title>
<script>
function sayHello() {
alert('Hello, World!');
}
</script>
</head>
<body>
<button onclick="sayHello()">Click Me</button>
</body>
</html>
```
On the other hand, **Angular.js** is a full-fledged web framework maintained by Google. It's designed for creating single-page applications (SPAs) with advanced data binding, routing, and modularity. Angular simplifies developing complex front-end apps but requires a bit more setup compared to Vanilla JS.
```html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>AngularJS Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.message = "Hello, AngularJS!";
});
</script>
</head>
<body>
<div ng-controller="myCtrl">
{{ message }}
</div>
</body>
</html>
```
### Building a Website from Scratch with Vanilla JavaScript
Let’s walk through the process of creating a simple website using HTML, CSS, and Vanilla JavaScript.
#### 1. Create the Project Folder
Start by creating a folder for your project.
```
/my-website
index.html
styles.css
script.js
```
2. Write the HTML
The **index.html** file contains the structure of your website.
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Website</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>Welcome to My Website</h1>
</header>
<section>
<p>This is a simple website built with Vanilla JavaScript.</p>
<button id="clickButton">Click Me</button>
</section>
<script src="script.js"></script>
</body>
</html>
```
3. Add Styling with CSS
The **styles.css** file contains your website’s appearance.
```css
body {
font-family: Arial, sans-serif;
text-align: center;
}
header {
background-color: #333;
color: #fff;
padding: 1rem;
}
button {
padding: 0.5rem 1rem;
background-color: #007BFF;
color: white;
border: none;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
```
Try out JavaScript
4. Add JavaScript Interactivity
Continued.
TekTrain -building technologists.
0 Comments:
Post a Comment