-1

Im new to js and I have an issue,

This code works perfectly fine:

function test(args){

    return "12345 - "+args;
}

console.log(test("678910"));

But this code doesn't:

function test(args){
    if(args = ""){
    
    }
    return "12345 - "+args;
}
console.log(test("678910"));

[args] becomes undefined for some reason and I cant understand why, I suppose it has something to do with context, but I still dont understand why nothing works, help would be really appreciated!

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Fedya
  • 3
  • 1
  • 3
    `if(args = ""){` you're assigning `args` to an empty string here. You need to use `==` or `===` for comparison – Nick Parsons Sep 03 '20 at 14:36
  • Why args becomes undefined after this code is main thing that bothers me – Fedya Sep 03 '20 at 14:37
  • When I run your code `args` does **not** become undefined, it gets set to an empty string, which is due to your if-statement (`args = ""`) – Nick Parsons Sep 03 '20 at 14:37
  • Does this answer your question? [What is the correct way to check for string equality in JavaScript?](https://stackoverflow.com/questions/3586775/what-is-the-correct-way-to-check-for-string-equality-in-javascript) – Clint Sep 03 '20 at 14:41
  • I knew the difference between == and =, i just didnt notice my mistake, thanks to you all again – Fedya Sep 03 '20 at 14:43

4 Answers4

2

The comparison operator is ==, not =. args = "" is assigning args to an empty string, not comparing it. So you should use:

if(args == ""){
Anis R.
  • 6,656
  • 2
  • 15
  • 37
1

you have to use == in the if statement and also you have to make it do something if args == ""

if (args == "") {
    // Write something to do here.
}

if you don't want it to do anything whe it equals to "", use:

if (args != null) {
   return "12345 - "+args;
}
1

You need to replace = with == in your if Statement: Otherwise you are assigning an empty string to your args parameter.

function test(args){
    if(args == ""){
    
    }
    return "12345 - "+args;
}
console.log(test("678910"));

Also your if doesn't do anything so the return will aways be "12345 - "+args;

If you only want to return, in case args is set do something like this:

if (args) {
    return "12345 - "+args;
}
Chaz
  • 672
  • 1
  • 5
  • 19
0

This should work just fine ;)

   function test(args){
    if(args == ""){
    
    }
    return "12345 - "+args; }
    console.log(test("678910"));

Or you can use

    function test(args){
      if(args != null){
        return "12345 - "+args;
      }
    }
    console.log(test("678910"));
Pilatos
  • 21
  • 7