Learn JavaScript in Construct, part 2: language basics

31

Index

Features on these Courses

Stats

13,861 visits, 36,617 views

Tools

Translations

This tutorial hasn't been translated.

License

This tutorial is licensed under CC BY-NC 4.0. Please refer to the license text if you wish to reuse, share or remix the content contained within this tutorial.

Published on 24 Sep, 2021. Last updated 16 Dec, 2021

Variables

A variable is a name for a value stored in the computer's memory. If you've used variables in Construct's event sheet, such as global or local variables, the concept is similar. For example you could have a variable named score storing a number for the player's score. The value can be changed, or vary, hence the name variable.

Declaring and assigning variables

In JavaScript, variables are declared with the let keyword, followed by the name of the variable. The code below creates a variable named message.

let message;

A value, in this case a string (i.e. some text), can be assigned to this variable using the assignment operator =.

message = "Hello world!";

Now we can log this variable to the console. Here's the full code snippet.

let message;
message = "Hello world!";
console.log(message);

It's very common to declare a variable and immediately assign it a value, so both can be combined in to one statement like so:

let message = "Hello world!";

Multiple variables can also be declared using commas, with or without an assignment. For example:

let firstName, lastName, food = "pizza", drink = "cola";

Is equivalent to:

let firstName;
let lastName;
let food = "pizza";
let drink = "cola";

In general we recommend using the latter style with a let declaration for every variable as it is clearer.

You can assign a variable different values. The following code sets the message to First message! and then Second message!. The second assignment replaces the contents of the variable, so this will only log Second message!.

let message;
message = "First message!";
message = "Second message!";
console.log(message);

What happens if you never assign a value? The default value of a variable in JavaScript is undefined, a special value that means "nothing".

let message;
console.log(message);

Avoid using this - undefined in a variable usually means you made a mistake. It's a good idea to always initialise a variable to something to help avoid this.

Rules for using variables

You must declare a variable before using it. The following code will result in an error as it tries to use message before declaring it.

// ReferenceError: Cannot access 'message' before initialization
console.log(message);
let message = "Hello world!";

You cannot declare the same variable name twice.

let message = "First message!";
// SyntaxError: Identifier 'message' has already been declared
let message = "Second message!";

Variable names can only contain letters, digits, or the symbols $ and _. However the first character cannot be a digit. Also the variable name cannot be a reserved word, i.e. a keyword used by the JavaScript language, such as let.

// Valid variable names:
let userName;
let user_name;
let testing123;

// Invalid variable names:
let user-name;	// dash '-' not allowed
let 9slice;	// starting with digit not allowed
let let;	// keyword not allowed

Note also that JavaScript is case-sensitive, i.e. message is regarded as a different variable name to Message or MESSAGE. This is in contrast to Construct's event sheets, which are usually case-insensitive.

It's a good idea to always use descriptive variable names to help make your code easy to understand. There are also different naming conventions, such as whether you use underscores (first_name) or "camel case" (firstName). It doesn't matter much which you pick - just be consistent, and if you work in a team, make sure everyone agrees on the same naming style.

Constants

You can also declare a constant, which is like a variable that cannot be modified. These are declared with const instead of let. Some values never need to change when your code runs, such as the mathematical constant pi, or the maximum number of login attempts allowed. Trying to change these values should be an error, and const enforces this.

// Declare a constant
const PI = 3.141592653589793;

// TypeError: Assignment to constant variable.
PI = 4;

The naming rules for constants are identical to variables, but a common convention is to name constants with all uppercase names to help tell them apart from variables.

var

You may come across old JavaScript code using var to declare variables:

var message = "Hello world!";

You can assume this works the same as let. Avoid using it though, as it is an old feature with some odd quirks which we won't go in to here. Modern code should only use let.

  • 5 Comments

  • Order by
Want to leave a comment? Login or Register an account!
  • Congratulations!! Very Clear and Objective in the explanations!!!

  • Thank you Ashley, I've been wanting to learn Javascript for sometime now. I tried another console but it was to hard to setup. Using Construct makes it simple. I am not a full time code developer, but the first language I learned on was basic using a mainframe at the Community College way back when. I am a retired teacher working with an English professor developing his English course for online learning. I'm looking forward to implementing the JavaScript in my project to make easier to develop and make it efficient.

  • You might consider including "scope" in the "VAR" section and why "var" is quirky.

      • [-] [+]
      • 3
      • Ashley's avatar
      • Ashley
      • Construct Team Founder
      • 3 points
      • (1 child)

      As explained in part 1 this tutorial isn't intended to go in to detail about the quirks of old legacy features. If you stick to let/const then you don't need to learn about all those quirks.