×

# Data Types & Variables

## Exam Questions

Exam questions on this topic

## Introduction

In this first section, we will experiment with how variables are declared and assigned, as well as considering some of the different types of values in programming. You should have read the above slides to learn the relevant theory, but here is a recap of the programming basics you will need to complete the below tasks.

// You can declare a variable and assign it an initial value using the
// following. Note that each statement must have a semicolon at the end.
var x = 3;

// You can assign a new value to any existing variable:
x = 4;

// console.log(...) allows you to output the 'console'.
// In general, you can access the console by opening
// your browser's debugging tools; for Chrome you can
// press Ctrl + Shift + I. On this page any console outputs
// will appear on the right.
console.log(x);

// You can get the program to prompt the user
// for a value using 'prompt'.
var y = prompt("Please enter a number");
console.log("The number entered was "+y);


## Mini Task #1: Declaring and Assigning Values

Write code that carries out the following:

1. Declares a variable x and assigns it the value 3.
2. Declares a variable y and assigns it the value 4.7.
3. Declares a variable z which is the sum of x and y.
4. Outputs z to the console.
Reset to Original Code     Fullscreen

## Mini Task #2: Types of values

Use the typeof operator to investigate the types of different values. Remember that JavaScript has a relatively small number of primitive types, Number (there is no distinction between integers and reals), String and Boolean. JavaScript has no 'character' type; characters are just considered to be strings of length 1.

Reset to Original Code     Fullscreen

## Mini Task #3: Converting between types.

We can convert between various primitive types. e.g. Number("43") converts the string/text "43" into an actual number, so that we can subsequently do 'number' stuff to it, e.g. add other numbers to it.

Reset to Original Code     Fullscreen

## Mini Task #4: Automatic type conversion

When we mix types, JavaScript attempts to convert them for you, without explicitly needing to use code such as Number(...). Guess what happens when the following code is run, and see if it matches your expectations. Note that * in programming is multiplication.

Reset to Original Code     Fullscreen