Reader small image

You're reading from  JavaScript from Beginner to Professional

Product typeBook
Published inDec 2021
Reading LevelBeginner
PublisherPackt
ISBN-139781800562523
Edition1st Edition
Languages
Tools
Right arrow
Authors (3):
Laurence Lars Svekis
Laurence Lars Svekis
author image
Laurence Lars Svekis

Laurence Svekis is an experienced web application developer. He has worked on multiple enterprise-level applications, hundreds of websites, business solutions, and many unique and innovative web applications. He has expertise in HTML, CSS, JavaScript, jQuery, Bootstrap, PHP, and MySQL and is also passionate about web technologies, web application development, programming, and online marketing with a strong focus on social media and SEO. He is always willing to help his students experience what technology has to offer and looks forward to sharing his knowledge and experiences with the world.
Read more about Laurence Lars Svekis

Maaike van Putten
Maaike van Putten
author image
Maaike van Putten

Maaike is a software consultant and trainer with a passion for sharing her expertise to empower others in their careers. Her love for software development shows in the numerous software development projects she participated in and the many certifications she obtained. She has designed and delivered a broad spectrum of training courses catering to beginners and seasoned developers in Java, Python, C# and many other languages and frameworks. Next to that, she has authored multiple books and online courses through multiple platforms reaching over 500,000 learners across the globe.
Read more about Maaike van Putten

Codestars By Rob Percival
Codestars By Rob Percival
author image
Codestars By Rob Percival

Rob Percival is a highly regarded web developer and Udemy instructor with over 1.7 million students. Over 500,000 of them have taken Rob's Complete Web Developer Course 2.0, as well as his Android Developer and iOS Developer courses.
Read more about Codestars By Rob Percival

View More author details
Right arrow

Writing JavaScript code

So, we now have lots of context, but how do you actually write JavaScript code? There are some important things to keep in mind, such as how to format the code, using the right indentation level, using semicolons, and adding comments. Let's start with formatting code.

Formatting code

Code needs to be formatted well. If you have a long file with many lines of code and you didn't stick to a few basic formatting rules, it is going to be hard to understand what you've written. So, what are the basic formatting rules? The two most important for now are indentations and semicolons. There are also naming conventions, but these will be addressed for every topic that is yet to come.

Indentations and whitespace

When you are writing code, often a line of code belongs to a certain code block (code between two curly brackets { like this }) or parent statement. If that is the case, you give the code in that block one indentation to make sure that you can see easily what is part of the block and when a new block starts. You don't need to understand the following code snippet, but it will demonstrate readability with and without indentations.

Without new lines:

let status = "new"; let scared = true; if (status === "new") { console.log("Welcome to JavaScript!");  if (scared) { console.log("Don't worry you will be fine!"); } else { console.log("You're brave! You are going to do great!"); } } else { console.log("Welcome back, I knew you'd like it!"); }

With new lines but without indentation:

let status = "new";
let scared = true;
if (status === "new") {
console.log("Welcome to JavaScript!");
if (scared) {
console.log("Don't worry you will be fine!");
} else {
console.log("You're brave! You are going to do great!");
}
} else {
console.log("Welcome back, I knew you'd like it!");
}

With new lines and indentation:

let status = "new";
let scared = true;
if (status === "new") {
  console.log("Welcome to JavaScript!");
  if (scared) {
    console.log("Don't worry you will be fine!");
  } else {
    console.log("You're brave! You are going to do great!");
  }
} else {
  console.log("Welcome back, I knew you'd like it!");
}

As you can see, you can now easily see when the code blocks end. This is where the if has a corresponding } at the same indentation level. In the example without indentations, you would have to count the brackets to determine when the if block would end. Even though it is not necessary for working code, make sure to use indentation well. You will thank yourself later.

Semicolons

After every statement, you should insert a semicolon. JavaScript is very forgiving and will understand many situations in which you have forgotten one, but develop the habit of adding one after every line of code early. When you declare a code block, such as an if statement or loop, you should not end with a semicolon. It is only for the separate statements.

Code comments

With comments, you can tell the interpreter to ignore some lines of the file. They won't get executed if they are comments. It is often useful to be able to avoid executing a part of the file. This could be for the following reasons:

  1. You do not want to execute a piece of code while running the script, so you comment it out so it gets ignored by the interpreter.
  2. Metadata. Adding some context to the code, such as the author, and a description of what the file covers.
  3. Adding comments to specific parts of the code to explain what is happening or why a certain choice has been made.

There are two ways to write comments. You can either write single-line comments or multi-line comments. Here is an example:

// I'm a single line comment
// console.log("single line comment, not logged");
/* I'm a multi-line comment. Whatever is between the slash asterisk and the asterisk slash will not get executed.
console.log("I'm not logged, because I'm a comment");
*/

In the preceding code snippet, you see both commenting styles. The first one is single-line. This can also be an inline comment at the end of the line. Whatever comes after the // on the line will get ignored. The second one is multiline; it is written by starting with /* and ending with */.

Practice exercise 1.4

Adding comments:

  1. Add a new statement to your JavaScript code by setting a variable value. Since we will cover this in the next chapter, you can use the following line:
    let a = 10;
    
  2. Add a comment at the end of the statement indicating that you set a value of 10.
  3. Print the value using console.log(). Add a comment explaining what this will do.
  4. At the end of your JavaScript code, use a multiple-line comment. In a real production script, you might use this space to add a brief outline of the purpose of the file.

Prompt

Another thing we would like to show you here is also a command prompt. It works very much like an alert, but instead, it takes input from the user. We will learn how to store variables very soon, and once you know that, you can store the result of this prompt function and do something with it. Go ahead and change the alert() to a prompt() in the Hi.html file, for example, like this:

prompt("Hi! How are you?");

Then, go ahead and refresh the HTML. You will get a popup with an input box in which you can enter text, as follows:

Graphical user interface, application

Description automatically generated

Figure 1.5: Page prompting for use input

The value you (or any other user) enter will be returned to the script, and can be used in your code! This is great for getting user input to shape the way your code works.

Random numbers

For the purpose of fun exercises in the early chapters of this book, we would like you to know how to generate a random number in JavaScript. It is absolutely fine if you don't really understand what is going on just yet; just know that this is the command to create a random number:

Math.random();

We can do it in the console and see the result appear if we log it:

console.log(Math.random());

This number will be a decimal between 0 and 1. If we want a number between 0 and 100, we can multiply it by 100, like this:

console.log(Math.random() * 100);

Don't worry, we will cover mathematic operators in Chapter 2, JavaScript Essentials.

If we don't want to have a decimal result, we can use the Math.floor function on it, which is rounding it down to the nearest integer:

console.log(Math.floor(Math.random() * 100));

Don't worry about not getting this yet. This will be explained in more detail further on in the book. In Chapter 8, Built-In JavaScript Methods, we will discuss built-in methods in more detail. Until then, just trust us that this does generate a random number between 0 and 100.

Previous PageNext Page
You have been reading a chapter from
JavaScript from Beginner to Professional
Published in: Dec 2021Publisher: PacktISBN-13: 9781800562523
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (3)

author image
Laurence Lars Svekis

Laurence Svekis is an experienced web application developer. He has worked on multiple enterprise-level applications, hundreds of websites, business solutions, and many unique and innovative web applications. He has expertise in HTML, CSS, JavaScript, jQuery, Bootstrap, PHP, and MySQL and is also passionate about web technologies, web application development, programming, and online marketing with a strong focus on social media and SEO. He is always willing to help his students experience what technology has to offer and looks forward to sharing his knowledge and experiences with the world.
Read more about Laurence Lars Svekis

author image
Maaike van Putten

Maaike is a software consultant and trainer with a passion for sharing her expertise to empower others in their careers. Her love for software development shows in the numerous software development projects she participated in and the many certifications she obtained. She has designed and delivered a broad spectrum of training courses catering to beginners and seasoned developers in Java, Python, C# and many other languages and frameworks. Next to that, she has authored multiple books and online courses through multiple platforms reaching over 500,000 learners across the globe.
Read more about Maaike van Putten

author image
Codestars By Rob Percival

Rob Percival is a highly regarded web developer and Udemy instructor with over 1.7 million students. Over 500,000 of them have taken Rob's Complete Web Developer Course 2.0, as well as his Android Developer and iOS Developer courses.
Read more about Codestars By Rob Percival