code-8
code-8

Reputation: 58702

How do I know when to use if or switch statement?

I want to construct my data object base on my url params.

var $data = {};

if(params.assessmentId !== undefined){
    $data.assessmentId = params.assessmentId;
}
if(params.classroomId !== undefined){
    $data.classroomId = params.classroomId;
}
if(params.studentId !== undefined){
    $data.studentId = params.studentId;
}
if(params.courseContentId !== undefined){
    $data.courseContentId = params.courseContentId;
}

console.log($data);

I want to check if they're exist first, then set it accordingly.

Is what I have is good enough ?

Should I use a switch statement instead ?

Upvotes: 1

Views: 65

Answers (5)

Robert Moskal
Robert Moskal

Reputation: 22553

A switch statement won't really work in your situation because you keep examining different keys. Switch works on a single value, so you might use it to do different things based on the value of courseContentId:

switch(params.courseContentId ) {
    case undefined:
        code block
        break;
    case 10:
        code block
        break;
    default:
        default code block
}

Upvotes: 2

Mahesh Kapoor
Mahesh Kapoor

Reputation: 254

If you have only these number of cases then it looks ok !! but if you have many conditions to check then you would have a check, a jump to the next clause, a check, a jump to the next clause and so on.

On the other hand, With "switch" the JVM loads the value to compare and iterates through the value table to find a match, which is faster in most cases.

Note: A switch statement is not always faster than an if statement. It scales better than a long list of if-else statements as switch can perform a lookup based on all the values. However, for a short condition it won't be any faster and could be slower.

Upvotes: 1

Bergi
Bergi

Reputation: 664969

Is what I have is good enough?

Yes.

If you want it shorter, use a loop over the expected property names.

Should I use a switch statement instead?

No. A switch statement has a completely different purpose.

Upvotes: 4

Strelok
Strelok

Reputation: 51461

In your provided example you actually don't need the if statements all. Just assign $data properties as you're doing. If something in params is undefined it will not reflect on your $data object.

PS. A switch statement will not help you in any way. A switch statement is used to branch your code depending on multiple possible values of THE SAME variable. Not different ones.

Upvotes: 1

baao
baao

Reputation: 73251

I wouldn't use switch or if, but this code that will do the same, only better:

var $data = {};
var params = {};
params.assessmentId = 11;

for (var n in params) {
    $data[n] = params[n]
}
console.log($data);

You are only copying values from one object to another, so you can simply loop over it and your $data object will only receive values set in params.

Upvotes: 2

Related Questions