Understanding JavaScript Basics: A Beginner's Guide

Welcome to this introductory guide to JavaScript, where we will explore one of the most powerful and popular programming languages ​​on the web. If you’re already familiar with using HTML and CSS to create web pages, JavaScript is the final piece you need to turn your sites into engaging, life-like experiences.

Understanding JavaScript Basics: A Beginner's Guide
Understanding JavaScript Basics: A Beginner's Guide

Origins of JavaScript

In 1995, Brendan Ike developed JavaScript with the goal of making it easier to add interactive and dynamic elements to websites. The idea was to make web programming easier and faster. Since then, JavaScript has evolved into a versatile language.

Uses of JavaScript

JavaScript is no longer limited to creating interactive effects on web pages. Today, it is used in a wide range of applications such as:

  • Programming robots.
  • Writing game scripts using Unity.
  • Creating script editors.

The possibilities of JavaScript are limitless, and it is now an essential part of developing web, mobile, and even desktop applications.

What will you learn?

Throughout this guide, you will learn the basics of the JavaScript programming language, and you will learn how to use the common tools that programmers rely on in their daily work.

In addition, you will have the opportunity to apply what you learn practically through a set of exercises that follow each section to reinforce the concepts learned.

A Look at the History of JavaScript

Before we begin, let's take a moment to talk about the history of this wonderful language and how it has become one of the mainstays of the modern programming world.

Let's start our journey with JavaScript!

History of JavaScript

In 1995, in a short period of time of no more than ten days, Brendan Icke invented JavaScript while working with Netscape to develop its then-popular browser, Netscape Navigator, which was one of the first web browsers. Today, we use more modern browsers such as Google Chrome, Mozilla Firefox, Apple Safari, and Microsoft Edge to browse the Internet.

What were websites like before JavaScript?

Before JavaScript, websites were based entirely on HTML and CSS, with some additions such as Java Applets or Plugins used to add interactive functionality. However, this approach was complex and impractical, which led to the invention of JavaScript as a simpler and more efficient solution.

JavaScript is not Java

It is important to clarify that JavaScript has nothing to do with Java, despite the similarity in name. Initially, JavaScript was known as LiveScript, but the name was changed to JavaScript as a marketing strategy to capitalize on the huge popularity of the Java language at the time.

JavaScript evolved into an official standard

As the popularity of JavaScript grew, different versions of it emerged, which led to the need for standardization. Therefore, JavaScript was submitted to ECMA International to develop an official standard for the language, which is known as ECMAScript.

ECMAScript Releases

Early versions of the standard, such as ES5 and ES6, had indicative numbers, but over time, the standard has moved to using year-based numbers to streamline the release cycle. For example, we now have versions such as ES2016, ES2017, and beyond.

Where JavaScript stands today

Despite its complicated name history, JavaScript has become one of the most popular programming languages ​​in the world, and is now considered one of the three pillars of front-end web development, along with HTML and CSS.

Conclusion: JavaScript has evolved from a simple tool for developing websites to a powerful programming language used in a wide variety of applications, making it an indispensable element of the modern programming world.

Getting to Know the JavaScript Console

What is the Console? The JavaScript Console is a powerful tool that helps you write and execute JavaScript code directly within your browser. You’ll rely on it a lot to experiment with the code you’ll learn throughout the course, and it’s a flexible environment to test ideas and quickly experiment with code.

How ​​to Access the Console?

If you’re using Google Chrome, here are the steps:

  1. Open the Developer Tools:
  • Right-click anywhere on the page, then choose Inspect.
  • Or use the keyboard shortcuts:
    • On Mac: Press Command + Option + J.
    • On Windows: Press Ctrl + Shift + J.
  1. Open the Console:
    After opening the Developer Tools, click on the Console tab to access the Console.
Console Log Firefox
Console Log Firefox

If you are using a browser other than Chrome, you can search for the method on the Internet, then return to the console to continue.

Write the first code in the console

Now, with the console open, let's write the first line of JavaScript code:

  • Try writing your name directly. But you will encounter an error if you do not write it correctly. Why? In JavaScript, texts must be represented as "strings" by enclosing them in quotes, like this:
"Mahmoud"
Console Log String
Console Log String

Create an Alert Window

Let's try something more exciting! Write the following code in the console to create an alert window that displays a message:

alert("Hello Mahmoud, how are you?");

When executed, a pop-up message will appear in the browser saying: "Hello Mahmoud, how are you?"

Console Alert
Console Alert

Testing small code in the console

The console is a great place to test small code or code that you're not sure how to do. But what about longer code? That's where a code editor comes in.

Why use a code editor?

Writing code directly in the console can be a pain when dealing with larger programs, such as:

  • If you want to write more than one Alert message, you'll need to use Shift + Return for each new line instead of the regular Return key.

So, it's better to write the code in a code editor like VS Code, Atom, or Sublime Text, and then copy and paste it into the console to test it.

Using console.log

Instead of using alert for everything, you can use:

console.log("Hello Mahmoud");
Console Log
Console Log

This will display the text in the console instead of annoying the user with repeated alert messages.

The JavaScript console is a great tool for experimenting with code and understanding programming concepts, but it's not the best solution when working on large projects. Using a code editor makes it easier to develop longer, more complex programs.

Experiment with JavaScript in the browser

Work directly in the browser You can experiment and test your coding ideas directly in the browser using the Developer Tools. If you're used to using HTML or CSS, you may have used the Developer Tools to experiment with style changes. Now you can use the same tools to experiment with JavaScript code in an easy and safe way.

Why are the Developer Tools a great environment?

The Developer Tools are a "sandbox" for experimenting with code. In other words, they're a space where you can tinker with your code without any long-term consequences. You can use it to:

  1. Debugging:
  • If you encounter problems with your code, you can use developer tools to identify and fix errors.
  1. Testing new code:
  • Try out a new piece of code you just learned to see how it works.

Displaying errors and warnings

If you open any site that uses JavaScript, you can see errors or warnings in the Console. The Console displays the following:

console.error('This is an error');
console.warn('This is a warning');
  1. Errors:
  • When there is a bug in the code.
  1. Warnings:
  • Notifications about things that may not currently affect the site, but are worth paying attention to.
  1. Output from console.log:
  • Any text or data that was printed using this method.
Console Error and Warning
Console Error and Warning

Error Messages During the Course

As you learn in this course, you may see some warnings or errors from the sites you visit while using the console. Don't worry, this is very common and will not affect the code you write or learn.

How ​​to benefit from the console?

  • Try shortcodes to get an immediate understanding of how they work.
  • Check for errors if your code doesn't work as expected.
  • Observe the results directly to learn faster.

The developer tools in the browser are not just for modifying the design, they are a safe and flexible environment for experimenting with JavaScript code and debugging. Whether you are testing a new idea or trying to solve a problem, the developer tools are an essential tool for every programmer.

Next Step You have started to discover the power of JavaScript in making websites more interactive and dynamic. This is just the beginning, and we are ready to dive deeper to explore more about the language and how to use it in professional ways.

Introduction to Data Types

Everything around us can be represented in the form of data; whether it is the result of your first math test, the conversation you had with a loved one, or even your decision to sit down to watch a particular video or read this article.

Data is what helps us understand the world around us, recognize trends, form informed assumptions, and make informed decisions in the future.

In programming, data and data types form the basis of any programming language, as they help us organize information and determine how our programs work.

When you open your Facebook page, what do you see?

  • Your name
  • The date of your last post
  • A list of updates you have shared
  • The number of likes and comments on your posts All this information is collected and processed to appear in an organized manner for visitors to your page.

When you look at your bank account, you see:

  • Account balance
  • Details of each transaction
  • The name of the company you made the purchase from All this data is organized and presented to you in an orderly manner.

Why are data types important? It is important to be aware of the data types you are using, and to know when it is best to use each type. In this lesson, you will learn how to define and work with primitive data types in JavaScript such as:

  • Numbers
  • Strings
  • Booleans
  • Undefined
var booleanValue = true;
var numericalValue = 354;
var stringValue = "This is a String";
var stringObject = new String("This is a String Object");
var undefifindValue;
console.log(typeof booleanValue) // displays "boolean"
console.log(typeof numericalValue) // displays "number"
console.log(typeof stringValue) // displays "string"
console.log(typeof stringObject) // displays "object"
console.log(typeof undefindValue) // displays "undefind"
Javascript DataTypes
Javascript DataTypes

Once you master these types of data, you will learn how to store data in variables so that you can reuse and manipulate it throughout your code.

Comments in JavaScript

In programming, comments are a way to write text within code to clarify what the code is doing or to provide hints to other developers or even yourself when reviewing the code later.

While a computer understands and executes code, it can be difficult for humans to understand, especially as the code becomes more complex. Therefore, developers use comments to explain parts of the code in human-understandable language.

In JavaScript, there are two types of comments:

  1. Single-line comments: These are written after double slashes (//).
  2. Multi-line comments: These are written between slashes and an asterisk (/* */).
// One Line Comment
/*
   Multi Line Comments
   ...etc
*/

Importance of Comments

Comments are not implemented by the JavaScript interpreter, which means you can write anything you want inside the comment. But it is better to make the comments useful and clear, for example:

// This Comment Explain The Code Below
let word = "hello"; // Variable

Let's take an example of a code I wrote earlier that was difficult to understand: Of course, we are now focusing on the comments and not on explaining the codes themselves, those codes will be explained in the future in boring detail, God willing.

for (let i = 0; i < arr.length; i++) {
   // Do Thing Here
}

It seems that the code contains a function, a loop, and some variables with unclear names. If you had used comments explaining what each part does, it would have been easier to understand. For example:

/* 
   This function make a string reversed 
   like "Mahmoud" will be reversed to "duomham"
*/

function reverseWord(word) {
  let reversed = "";
  for (let i = word.length - 1; i >= 0; i--) {
    reversed += word[i];
  }
  return reversed;
}

console.log(reverseWord('Mahmoud'));
ReverseWord Function
ReverseWord Function

Using Comments in Exercises

In some of the exercises in this lesson, you may find comments that give you hints or instructions for completing the code. We encourage you to use comments in your own code to explain anything you've written that is unclear, whether in the exercises or elsewhere. This will develop good programming habits and improve the readability of your code if you need to refer back to it in the future.

Strings in JavaScript

You've used strings before, perhaps without realizing it. For example, when you write a message inside the console.log() function, that message is actually a string in JavaScript. For example:

console.log("Hello, world!");

In this example, "Hello, world!" is a string. Strings can contain single characters like "h", or even numbers like the string "123".

The important thing here is that you need to use quotation marks to indicate that the text is a string. These marks can be either single quotes ' or double quotes ". However, the marks must match, i.e. you cannot use single quotes at the beginning of the string and double quotes at the end.

For example, if you try to pass a string to console.log without using quotes, you will get an error:

console.log(hello);
Javascript ReferenceError
Javascript ReferenceError

In this example, JavaScript will return a ReferenceError error, because the JavaScript engine thinks you are referring to a variable called hello instead of a string containing the value "hello". We haven't covered variables yet, but the important thing here is to remember to use quotes when working with strings.

If you added the quotes correctly, the string will be printed in the console successfully:

console.log("hello");
Console Log a String
Console Log a String

Now the string will appear correctly in the console.

Variables in JavaScript

What can you do with the data you've worked with? Up until now, all the data you've worked with has been for one-time use only. For example, when you define a string like "hello", it is printed and then expires, and eventually that string disappears. But what if you need to store that data for later use or modification? That's where variables come in.

You may have heard of variables before, perhaps in math classes. For example, if you have a variable called x and its value is set to 5, then we have the expression x + 1. Since x has the value 5, we can replace x with the value 5 so that the expression becomes: 5 + 1, which equals 6.

In JavaScript, variables store data just like we did in The previous example where we stored the value 5 in the variable x. Variables are not limited to storing numbers only, you can store any type of data inside them.

To define a variable in JavaScript, we use the keyword let or var, followed by the variable name and the assignment operator =, then the value you want to store inside the variable.

For example, let's take my cat Kitty. We can create a variable called name and store the value "Kitty" (the cat's name) in it. To store her age, we can create another variable called age and give it the value 3, since Kitty is 4 years old.

Here's the following example:

let name = "Kitty"; // Store the cat's name
let age = 4; // Store the cat's age

Over time, when Kitty celebrates her next birthday, I can use the variable age to increment her age by one, so that she is 5 years old after the update.

age = age + 1; // Increment Kitty's age by one year

So, the variable age will now have the value 5, meaning that Kitty is 5 years old.

String Index in JavaScript

In JavaScript, strings are a collection of characters, and each character in the string has its own index. The count starts from 0, meaning that the first character in the string is at position (index) 0, the second is at position 1, and so on.

Example:

let greeting = "Hello";
console.log(greeting[0]); // will print "H" because "H" is the first character in the string.
console.log(greeting[1]); // will print "e" because "e" is the second character in the string.

If you want to access a specific character in the string, you can use index. For example, to access the third character in the string "Hello", you would write:

let thirdCharacter = greeting[2]; // the character at index 2 is "l"
console.log(thirdCharacter); // will print "l"

Escaping Strings

Sometimes you may need to include special characters in a string, such as quotation marks (" or ') or carriage returns (\n). In these cases, we use escaping, which means adding a backslash (\) before the special character to indicate that it is part of the string and has no special function.

Here are some examples:

1. Using quotes within a string:

let quote = "\"JavaScript is fun!\" said Mahmoud.";
console.log(quote); // will print: "JavaScript is fun!" said Mahmoud.

2. Using single quotes within a string:

let quote = '\'JavaScript is fun!\' said Mahmoud.';
console.log(quote); // will print: Mahmoud said: 'JavaScript is fun!'

3. Add a new line to the string:

let message = "Welcome to the JavaScript course!\nGood luck.";
console.log(message);
// Prints:
// Welcome to the JavaScript course!
// Good luck.

4. Using backslash in the string:

let filePath = "C:\\Users\\Mahmoud\\Documents";
console.log(filePath); // Prints: C:\Users\Mahmoud\Documents

Using escaping, you can include these special characters within the string without affecting the execution of the program.

Boolean Value in JavaScript

In JavaScript, Boolean is a data type that is used only The values: true (true) and false (false). It can be used to represent states that rely on logic like yes/no, on/off, true/false, or 1/0, and these values ​​are the basis of programming logic.

How ​​does Boolean work?

When comparing data (such as numbers or strings), the result will always be a boolean value: either true or false. This allows you to make logical decisions based on those comparisons.

Examples of comparisons using Boolean:

  1. Comparing numbers:
let x = 5;
let y = 10;
console.log(x > y); // will print false because 5 is not greater than 10
console.log(x < y); // will print true because 5 is less than 10
  1. Comparing Strings:
let str1 = "apple";
let str2 = "orange";
console.log(str1 === str2); // will print false because "apple" is not equal to "orange"
console.log(str1 === "apple"); // will print true because "apple" is equal to "apple"
  1. Comparing Using Boolean Values ​​Directly:
let isActive = true;
console.log(isActive); // will print true

Comparing different data types:

When comparing different data types, it can happen that the comparison is incorrect or leads to unexpected behavior. So it is important to know how to compare different types.

console.log(5 == "5"); // will print true because the comparison does not distinguish between types
console.log(5 === "5"); // will print false because comparing using === requires the types to be the same

Using Booleans in Conditional Statements:

Boolean values ​​are used extensively in conditional statements (such as if and else):

let isUserLoggedIn = true;

if (isUserLoggedIn) {
   console.log("Welcome, user!"); // will print if the value is true
} else {
   console.log("Please log in."); // Will print if the value is false
}

Null, Undefined, and NaN in JavaScript

In JavaScript, there are some values ​​that may be confusing at first because they look similar, but have different meanings. Among these values ​​are null, undefined, and NaN.

null

  • null is a data type that represents empty or nothing. When you assign the value null to a variable, it means that you have intentionally assigned a null or non-existent value.
  • For example:
let x = null;
console.log(x); // Will print null

Here, the variable x has been assigned to the value null, which means that the variable does not hold a valid or existing value.

undefined

  • undefined is a data type that expresses the absence of a value, but not null values. If you declare a variable without assigning it a value, that variable will have the value undefined.
  • For example:
let y;
console.log(y); // will print undefined

In this example, the variable y was declared but did not get a value, so its value is undefined.

The difference between null and undefined:

  • null is a null value that was assigned manually.
  • undefined indicates the absence of a value, and usually occurs when a variable is declared without assigning a value.

NaN

  • NaN (Not a Number) is a special data type that means that the calculation did not produce a valid number. This usually happens when you try to perform an operation on values ​​that are not convertible to numbers.
  • For example:
let result = "hello" * 2;
console.log(result); // will print NaN because "hello" cannot be multiplied by a number

Comparing the values ​​null, undefined and NaN:

  • When comparing null and undefined using ==:
console.log(null == undefined); // will print true

This comparison is considered true because null and undefined are values ​​that indicate the absence of a value in an undefined way but there is a difference between them when compared using ===:

console.log(null === undefined); // will print false

Conclusion

We have reached the end of our article on the basics that you should know about JavaScript. Now, with a solid understanding of the JavaScript language, from its history to its tools like the console, from dealing with different types of data to how to write useful comments, you’re ready to move forward on your coding journey. Learning JavaScript is a crucial step in building powerful and flexible web applications. Don’t forget that practice is key! Use what you’ve learned here to continually develop your skills and experiment with code yourself. If you keep exploring and applying, you’ll soon become a seasoned JavaScript developer.

Comments