COMPUTER SCIENCE CAFÉ
  • WORKBOOKS
  • BLOCKY GAMES
  • GCSE
    • CAMBRIDGE GCSE
  • IB
  • A LEVEL
  • LEARN TO CODE
  • ROBOTICS ENGINEERING
  • MORE
    • CLASS PROJECTS
    • Classroom Discussions
    • Useful Links
    • SUBSCRIBE
    • ABOUT US
    • CONTACT US
    • PRIVACY POLICY
  • WORKBOOKS
  • BLOCKY GAMES
  • GCSE
    • CAMBRIDGE GCSE
  • IB
  • A LEVEL
  • LEARN TO CODE
  • ROBOTICS ENGINEERING
  • MORE
    • CLASS PROJECTS
    • Classroom Discussions
    • Useful Links
    • SUBSCRIBE
    • ABOUT US
    • CONTACT US
    • PRIVACY POLICY
JAVASCRIPT | VARIABLES AND USER INPUT
ON THIS PAGE
​SECTION 1 | WHAT ARE VARIABLES
​SECTION 2 | CREATING VARAIBLE
SECTION 3 | COMMENTING CODE
​SECTION 4 | NAMING RULES AND CONVENSIONS

​SECTION 5 | DEFINING, ASSIGNING AND CALLING
​SECTION 6 | CONCATENATION

SECTION 7 | USING THE WEB BROWSER CONSOLE
​SECTION 8 | USER INPUT
ALSO IN THIS TOPIC
GETTING STARTED

YOU ARE HERE | ​VARIABLES & USER INPUT
 OPERATORS

CONDITIONALS (IF STATEMENTS)
​ITERATION (LOOPS)
ARRAYS (LISTS)
FUNCTIONS

FURTHER JAVASCRIPT

Picture
SECTION 1 | WHAT ARE VARIABLES
A variable can be thought of as a container or a storage box where you can keep different types of information or data. Just like you might store toys in a toy box or books on a bookshelf, in programming, we use variables to store data like numbers, words, or even more complex information.

The purpose of variables
  • Storage | Variables allow us to store data that we can use and manipulate later in our program.
  • Reference | Once data is stored in a variable, we can refer to it by the variable's name whenever we need it.
  • Flexibility | Variables can change or "vary" (hence the name "variable"). This means that the data inside a variable can be updated or changed as needed.

​Imagine you're playing a video game, and you have a score. That score might start at 0 and increase as you progress. In the game's programming, a variable is used to store your score. As you earn points, the value inside that variable changes.

In simple terms, a variable is like a labelled jar where you can put something inside, look at it whenever you want, and even change its contents!
SECTION 2 | CREATING VARIABLES
In programming, before we use a container (or variable) to store information, we need to tell the computer that we're creating it. This is known as "declaring" a variable. In JavaScript, there are three main ways to declare a variable: using let, const, and var (var is an older method and is now commonly replaced with let).

USING 'let'
KEY FEATURE | The let keyword allows you to change the value stored in the variable later on.
HOW TO DECLARE | You start with the word let, followed by the name you want to give your variable.

let myName = ("King Bob");

USING 'const'
KEY FEATURE | The const keyword is used for variables whose values should not change. Once you set a value to a const variable, you can't change it later.
HOW TO DECLARE | You start with the word const, followed by the name you want to give your variable.

const myName = ("King Bob")

WHAT ABOUT NUMBERS?
You can use the same method with numbers but, if you want the program to know that they are numbers rather than text you simply do not put the numbers in speech marks

let number1 = 5;
SECTION 3 | COMMENTING CODE
Before we move on you should know about commenting code so you do not get confused when reading the code sample we provide. Commenting is a way to add notes or explanations within your code. These comments are ignored by the computer when the code runs, so they don't affect the behavior of your program. Instead, they're meant for developers to provide context, explanations, or to temporarily disable a portion of code.

Why Comment?
  • Clarity: To explain complex code logic, making it easier for others (and yourself) to understand later.
  • Collaboration: To communicate with other developers about certain parts of the code.
  • Deactivation: To temporarily prevent certain lines of code from running without deleting them.

Single-Line Comment
Single-line comments start with //. Everything after // on that line is considered a comment.

Multi-Line Comment
For longer comments that span multiple lines, you can use /* to start the comment and */ to end it.

    
​Commenting is a crucial practice in coding and makes you code look more professional. It helps make your code more understandable and maintainable, both for yourself and for others who might work on your code in the future. Always strive to write clear comments, especially for complex or non-obvious parts of your code.
SECTION 4 | NAMING RULS AND CONVENSIONS
To start coding like a pro you should consider the following when deciding on what names to give variables
​
VARIABLE NAMING RULES
✘ Cannot start a variable name with a number
​✘ Cannot contain spaces or special charaters
​✘ 
JavaScript has a list of reserved words (or keywords) that have special meanings, such as let, const, function, if, etc. These words cannot be used as variable names.

VARIABLE NAMING CONVENTIONS
To stick with good practice and to code like a pro you should:
✓ 
This is the most common convention in JavaScript. Start with a lowercase letter and capitalize the first letter of each subsequent concatenated word. Example: myFirstVariable, userInputData
✓ Meaningful names | Variable names should be descriptive enough to indicate their purpose or the kind of data they hold.
  • Good: userName, totalAmount
  • Bad: x, y, data1
​✓ Avoid Using Underscores at the Start | Starting a variable with an underscore (_variableName) is often used in some programming conventions to indicate a "private" variable. However, in JavaScript, this is just a convention and doesn't make the variable truly private.
​✓ Constants in Uppercase | If a variable is meant to remain constant (its value shouldn't change), it's a common convention to use all uppercase letters with underscores. Example: MAX_LIMIT, PI_VALUE
​✓  Avoid Abbreviations | Unless it's a widely accepted abbreviation, it's better to use full words to make the code more readable.
  • Good: maximumValue, userProfile
  • Bad: maxV, usrPrf
​✓ Use Singular and Plural Appropriately | If your variable represents a single item, use a singular name (e.g., user). If it represents multiple items, like an array, use a plural name (e.g., users).
SECTION 5 | DEFINING, ASSIGNING AND CALLING
DEFINING, CALLING AND ASSIGNING VALUES TO A VARIABLE
Creating a variable is called 'defining a variable' and using the variable is called 'calling the variable'. In the example below we define a variable call firstName and we assign the value 'Jane' to the variable. We then call the variable by outputting the value to the screen.

    
To run the code in Visual Studio Code, go to 'Run' then ' Run without debugging' and the output should show in the DEBUG CONSOLE.

UPDATING VARIABLE VALUES
Variables declared with let (and var, though it's less commonly used in modern JavaScript) can have their values updated. To update a variable's value, you simply assign a new value to it using the = assignment operator.

    
In the example above, we initially set the age variable to 25. Later in the code, we updated its value to 26.

REMEMBER | Variables declared with const cannot be reassigned. They are constant values, meaning once you set their value, you can't change it later in the code.
SECTION 6 | CONCATENATION
Concatenation is 'joining' pieces of text together. In programming, especially when working with text (strings), we often need to join two or more pieces together to form a single piece. This action of joining is called "concatenation."

Imagine you have two variables:

One has the firstName "Jane" stored in it.
The other  has the lastName "Doe" stored in it.
If you connect (or concatenate) these two variables, you'll get the output that reads "Jane Doe".

JavaScript uses the + symbol is used for concatenation when dealing with strings.

In the previous programs above we assigned a name to a variable and an age to a variable, below we look at joining these together in to a user friendly string(line of text).

    
Notice the space after the strings 'hello ' and before ' your are' etc. If you do not leave this space then each of the items that you join together will no have any space between them.
WORKING WITH NUMBERS
While the
+ symbol is used for addition with numbers, when used with strings, it performs concatenation

    
SECTION 7 | WEB BROWSER COLNSOLE
Why use Web Browser?
When you started learning to code, you used the debug console in Visual Studio Code (VSC) to see the results of your code. This is a great way to quickly test and view simple outputs. However, as you dive deeper into web development, especially when dealing with user interactions like getting input or manipulating web pages, you'll need an environment that behaves like a real-world web browser. That's where the web browser's console comes in.

What's the Web Browser Console?
The web browser console is a tool built into web browsers like Edge and Chrome. It allows developers to:
  • View messages, errors, and outputs from their code.
  • Test and run JavaScript code in real-time.
  • Inspect and interact with web page elements.
  • Debug their web applications.
It's like the VSC debug console but tailored for web interactions and provides a more realistic environment for web-based code.

How to Access the Console?
Microsoft Edge
  • Open Microsoft Edge.
  • Click on the three horizontal dots (⋯) in the top right corner to open the menu.
  • Hover over "More tools" and select "Developer Tools" from the dropdown. Alternatively, you can press F12 or Ctrl + Shift + I on your keyboard.
  • In the Developer Tools panel, click on the "Console" tab.

Google Chrome
  • Open Google Chrome.
  • Click on the three vertical dots (⋮) in the top right corner to open the menu.
  • Hover over "More tools" and select "Developer Tools" from the dropdown. Alternatively, you can press Ctrl + Shift + I (or Cmd + Option + I on Mac) on your keyboard.
  • In the Developer Tools panel, click on the "Console" tab.

As you progress in your coding journey, you'll find that different tools are better suited for different tasks. The VSC debug console is excellent for quick tests and outputs and as you further develop your JavaScript you will add HTML at this point this introduces another way of running your code, but for now getting used to VSC and the Web Browser console are valuable skills. By understanding and using both, you'll be better equipped to develop, test, and debug your web applications effectively.

GIVE IT A TRY
Copy and paste the following code into the console in your Web browser, after press 'Enter' to check how it works.

We suggest you continue to write your code in VSC and then copy it into the Web Browser console to test it.

    
SECTION 8 | USER INPUT
The first step is to ask or prompt the user for input. This can be done using various methods, depending on the platform or environment you're working in. In web-based JavaScript, the prompt() function is commonly used.

Capturing the Input
When the user provides input (e.g., by typing into a text box or selecting an option), the program captures that input as a value. This value is typically in the form of a string (text) or a number, but it can also be other data types depending on the context.

Storing the Input
Once captured, this value needs to be stored for future use or processing. This is where variables are used. A variable acts as a container or storage box for data. By assigning the captured input to a variable, the program can access and manipulate that data later on.

Using the Stored Input
With the user input now stored in a variable, the program can use it in various ways, such as performing calculations, making decisions, displaying it back to the user, or sending it to a server.

    
In the example above:
  • The prompt() function displays a dialog box where the user can type in their name.
  • The input provided by the user is captured and immediately stored in the userName variable.
  • The program then uses the stored input to greet the user by concatenating the input with a greeting message.

The principle of taking and storing user input in a variable revolves around the idea of interaction and data storage. By prompting users for information and then storing their responses in variables, programs can become dynamic and responsive, tailoring their behaviour and output to individual users' inputs.
Picture
MY FIRST CHALLENGE
OBJECTIVE
Write a program that asks the user for their name and favourite colour. Then, display a personalized message using both their name and colour.

TASKS
  1. Prompt the user to enter their name.
  2. Prompt the user to enter their favourite colour.
  3. Display a message to the user that says, "[Name], your favourite colour is [colour].
Picture
NAVIGATION
GETTING STARTED
​VARIABLES & USER INPUT
 OPERATORS
CONDITIONALS (IF STATEMENTS)
 ​ITERATION (LOOPS)
ARRAYS (LISTS)
FUNCTIONS

FURTHER JAVASCRIPT

This website uses marketing and tracking technologies. Opting out of this will opt you out of all cookies, except for those needed to run the website. Note that some products may not work as well without tracking cookies.

Opt Out of Cookies
Picture
SUGGESTIONS
We would love to hear from you
SUBSCRIBE 
To enjoy more benefits
We hope you find this site useful. If you notice any errors or would like to contribute material then please contact us.