1

How to use map in JavaScript?

function get(){
    var map = {'key1': 'value1', 'key2': 'value2'};
    if ('key1' in map) {
        return 'hello';
    } else {
        return 'kirti';
    }
}

When I'm calling the get() function on button click, it can't display any output. What is wrong in above function? Why does it not display any output?

3
  • 1
    What output would you expect? There's only returns. Commented May 10, 2014 at 7:54
  • are you sure it you called your function? because it returns (console.log/alert) Commented May 10, 2014 at 8:03
  • "Why does it not display any output?" Maybe because you are not doing anything with the return value? How are we supposed to know? Commented May 10, 2014 at 8:12

5 Answers 5

0

I can't really understang what the problem is, but I made a jsFiddle to show how to put the value of the return into a div:
jsFiddle http://jsfiddle.net/5v3M5/1/

var a = get();
document.getElementById('return').innerHTML = a;
Sign up to request clarification or add additional context in comments.

1 Comment

@user3614914 if this did help you kindly accept the answer or upvote because of the effort of the answerer
0

Not sure really what the expectation is - but if you just want to see if the property exists in the javascript object (map) you can just do this -

if(map.key1)
{
  // do what has to be done if the key exists
}

or in your case - you can simply use a ternary operator

return (map.key1 ? "hello" : "kirti"); 

The 'in' operator you are using will not work with 'if' as it is used to loop through all the properties of the object - more about for..in here

Comments

0

Try this:

var map = {'key1': 'value1', 'key2': 'value2'};
for (var key in map) {
    if(key == 'key1'){
        return 'hello';
    } else {
        return 'kirti';
    }
}

1 Comment

key == 'key1' .. it should be 'key1' == key ... static first so if you forget one = you will get error :)
0

If you have html like this :

Button : <input id="bt" type="button" value="BUTTON">

You can use jquery and the alert() function to show the result :

    $(document).ready(function(){
        $('#bt').on('click', function(){
            alert(get());
        });
    }); 

Comments

0
function get(){
var map = {'key1': 'value1', 'key2': 'value2'};
if ('key1' in map) {
   alert('hello');
} else {
    alert('kirti');
}

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.